angularjs - custom directive in ng-include not working

强颜欢笑 提交于 2019-12-11 10:49:12

问题


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

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>

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

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?

Thanks.


回答1:


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:

Controller changes:

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');
});

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.

Fiddle



来源:https://stackoverflow.com/questions/29271874/angularjs-custom-directive-in-ng-include-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!