angularjs - 自定义指令NG-包括不工作 [英] angularjs - custom directive in ng-include not working

查看:138
本文介绍了angularjs - 自定义指令NG-包括不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过这个片段在我的应用程序中使用BS3模式和正常工作。
http://jsfiddle.net/alexsuch/RLQhh/

I've tried this snippet for using bs3 modal in my application and it works fine. http://jsfiddle.net/alexsuch/RLQhh/

不过,我想换行的模式和其他一些HTML标记code成可重用的模板。

However,I want to wrap the code of modal and some other html tags into a template for reusability.

<div ng-controller="MainCtrl" class="container">
  <h1>Modal example</h1>
  <button ng-click="toggleModal()" class="btn btn-default">Open modal</button>
    <div ng-include src="'modal.html'"></div>
    <script type="text/ng-template" id="modal.html">
          <modal title="Login form" visible="showModal">
    <form role="form">
      <div class="form-group">
        <label for="email">Email address</label>
        <input type="email" class="form-control" id="email" placeholder="Enter email" />
      </div>
      <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" id="password" placeholder="Password" />
      </div>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
  </modal>
    </script>
</div>

下面是我的jsfiddle http://jsfiddle.net/wangjunji/gL7scbd9/

Here is my jsFiddle http://jsfiddle.net/wangjunji/gL7scbd9/

然后是question.The切换按钮只适用于第一次。
我知道,NG-include指令将创建一个子范围,这使得父范围变量可达,但我不知道要出这粘problem.Can谁能帮助?

Then comes the question.The toggle button only works for the first time. I know that ng-include directive will create a child scope which makes the variable in parent scope unreachable but I have no idea to work out this sticky problem.Can anyone help?

感谢。

推荐答案

我已经改变了你的codeA点点这样布尔值将驻留对象内,而现在你只需要观看的,而不是:

I've changed your code a little bit so the boolean value will reside inside an object, and now you just have to watch that instead:

控制器的变化:

mymodal.controller('MainCtrl', function ($scope) {
    $scope.modalObj = { showModal : false };
    $scope.toggleModal = function(){
        $scope.modalObj.showModal = !$scope.modalObj.showModal;
    };
  });

指令(主)的变化:

Directive (main) change:

scope.$watch(function () { return scope.modalObj.showModal; }, function(value){
    if(value == true)
      $(element).modal('show');
    else
      $(element).modal('hide');
});

和当然也行现在将参考而不是使用父/ ATTR关键字,一般来说,你应该尽量避免那些 scope.modalObj.showModal

And also of course the lines will now refer to scope.modalObj.showModal instead of using the parent/attr keywords, in general you should try to avoid those.

小提琴

这篇关于angularjs - 自定义指令NG-包括不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆