ken wang
ken wang

Reputation: 165

angularjs - custom directive in ng-include not working

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.

Upvotes: 1

Views: 1155

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

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

Upvotes: 1

Related Questions