【问题标题】:AngularJS: $watch not firing when value changed in directiveAngularJS:当指令中的值更改时,$watch 不会触发
【发布时间】:2014-07-01 07:23:05
【问题描述】:

我有自定义指令,将属性添加到链接函数内部的范围,然后添加一个监视。如果我从控制器更改范围属性的值,手表就会触发。如果我从指令内部更改相同的值,它不会被触发。

这里是一个例子:http://jsbin.com/bocixiha/3/edit

查看指令中的 setTimeout,此更改没有任何影响。

p.s:这只是我没有使用 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);
        });
      };
    }
  };  
});

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    Angular.js 需要收到更改通知。 setTimeout 本身并不会告诉 Angular 刷新模型;您需要使用$timeout 服务而不是setTimeout 或将setTimeout 回调的内容包装在scope.$apply() 中,以使Angular 意识到范围内的某些内容可能已更改。

    【讨论】:

    • 感谢您的快速响应,更改后需要 scope.$apply()。
    【解决方案2】:

    setTimeout替换为$timeout。当模型发生变化时,应该通知angular更新视图。使用$timeout函数会自动触发通知,否则需要调用$scope.$apply函数。

    【讨论】:

    • 也感谢您的快速响应。
    猜你喜欢
    • 2016-03-10
    • 2013-03-29
    • 2015-01-31
    • 2015-09-24
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    相关资源
    最近更新 更多