简体   繁体   English

AngularJS:指令中的值更改时,$ watch不触发

[英]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. 如果我从控制器更改了scope属性的值,则手表会着火。 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 这是一个示例: http : //jsbin.com/bocixiha/3/edit

See the setTimeout inside the directive, this change doesn't have any affect. 请参阅指令中的setTimeout,此更改没有任何影响。

ps: This is only a simulation of what i have an i'm not using the setTimeout but it works the same way. ps:这只是我有一个模拟,我没有使用setTimeout,但是它的工作方式相同。

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. 需要将更改通知Angular.js。 setTimeout by itself does not tell Angular to refresh the models; setTimeout本身不会告诉Angular刷新模型; 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. 您需要使用$timeout服务而不是setTimeout或将setTimeout回调的内容包装在scope.$apply()中,以使Angular知道范围中的某些内容可能已被更改。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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