简体   繁体   中英

AngularJS: $watch not firing when value changed in directive

I've got custom directive that add's a property to the scope in side the link function, then it add's a watch to it. If i changed the value of the scope property from the controller the watch gets fire. If i change that same value from inside the directive it won't get fired.

Here is an example: http://jsbin.com/bocixiha/3/edit

See the setTimeout inside the directive, this change doesn't have any affect.

ps: This is only a simulation of what i have an i'm not using the setTimeout but it works the same way.

var app = angular.module('app', []);

app.controller('myCtrl', function($scope) {
  $scope.changeProp = function() {
    $scope.options.someProperty = "Hello Stackoverflow";
  };
});

app.directive('mydir', function() {
  return {
    priority: 5001,
    restrict: 'A',
    compile: function(element, attrs) {
      return function(scope, element, attrs) {
        scope.options = {
          someProperty: "Hello World"
        };

        setTimeout(function() {
          console.log("Timeout Fired!");
          scope.options.someProperty = "This never gets set";
        }, 5000);

        scope.$watch('options.someProperty', function(n,o) {
          //This will fire when value changed from controller only.
          console.log("New: " + n + " Old: " + o);
        });
      };
    }
  };  
});

Angular.js needs to be notified of the change. setTimeout by itself does not tell Angular to refresh the models; you need to either use the $timeout service instead of setTimeout or wrap the contents of your setTimeout callback in scope.$apply() in order to make Angular aware of the fact that something on the scope might have been changed.

setTimeout替换为$timeout更改模型后,应通知angular更新视图。通过使用$timeout函数,该通知将自动触发,否则需要调用$scope.$apply函数。

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