简体   繁体   中英

Angular.js two-way binding do not work when update the $scope in the controller of custom directive?

I met this when I was writing a group of directives which can contact with each other.

Here is the CodePen url: http://codepen.io/jennieji/pen/mDGuw

Here is the JS code:

angular.module('app', [])
.directive('testDirective', function() {
  return {
    controller: function($scope){
      $scope.now = 0;

      this.update = function() {
        $scope.now++;
      };
    },
    link: function(scope) {
      scope.$watch(function(){
        return scope.now;
      }, function(newVal, oldVal) {
        element.append('<p>[LOG] $watch now:' + newVal + '</p>');
      }, true);
      scope.$watch('now', function(newVal, oldVal) {
        element.append('<p>[LOG] $watch now:' + newVal + '</p>');
      });
    }
  };
})
.directive('testUpdate', function() {
  return {
    require: '^testDirective',
    link: function(scope, element, attr, ctrl) {
      element.on('click', function(){
        ctrl.update();
        element.after('<p>[LOG] click now:' + scope.now + '</p>');
      });
    }
  }
});

Here is the HTML:

<div ng-app="app">
  <div test-directive>
    <p>{{ now }}</p>
    <button test-update>Update now</button>
  </div>
<div>

Since you are listening for the DOM click event:

element.on('click', function(){

Your scope changes will not take effect unless you $apply them:

link: function(scope, element, attr, ctrl) {
      element.on('click', function(){

        scope.$apply(function() {
          ctrl.update();
        });
        ctrl.update();
        element.after('<p>[LOG] click now:' + scope.now + '</p>');

      });
    }

$apply kicks off an Angular $digest loop and does the dirty check for the two-way bind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM