javascript - angularjs 指令 watch 未在对象函数属性上触发

标签 javascript angularjs

TL;DR:当属性是 函数 时,更新监视对象上的属性似乎不会触发监视。

实例

参见this Plnkr exampl .

可以通过单击示例中的按钮来更改 config 对象的属性。这些对象是同步的(指令和 Controller 之间),并且当属性更改时,指令中的 $watch 函数(在本例中只是增加计数器)被调用。 除了当函数属性改变时,这是我不明白的。

死例子

查看

<main-dir config="configObject"></main-dir> 

指令

myApp.directive('mainDir', function () {

    return {
        restrict: 'E',
        scope: {config: '='},
        link: function (scope, el) {

            //(initialisation code)
                           
            scope.$watch("config", function (config) {
                if (!config) return;
                // do stuff with config object
            }, true);

         }
     };
 });   

Controller

//init:
$scope.configObject = {
    propA: "value",
    propB: [1,2,3],
    propC: {key0: 3, key1: "value"},
    propD: function(x) {return x+1;}
}

//elsewhere:
$scope.configObject.propA = "other value"; //fires watch in directive
//or
$scope.configObject.propB = [3,2,1]; //fires watch in directive
//or
$scope.configObject.propB.push(5); //fires watch in directive
//or
$scope.configObject.propC = {key0: 1, key2: 34}; //fires watch in directive
//or
$scope.configObject.propC["key100"] = "newValue"; //fires watch in directive
//
// ... BUT ...
//
$scope.configObject.propD = function (x) {return x+2;} //does NOT fire watch in directive

所以,简而言之:我可以让 $watch 在对象属性发生更改时触发。但如果该属性是一个函数,这似乎不起作用。

解决方法:
当更改作为函数的属性时,我添加一行更改非函数属性来触发 watch ,如下所示:

$scope.configObject.propD = function (x) {/*...new function def...*/};
$scope.configObject.xxx = Math.random(); //<-- causes watch to fire

有谁知道为什么会这样吗?我可以让 $watch 在配置对象的 function 属性发生更改时触发吗?

谢谢!

最佳答案

scope.$watch("config.propD") 将监视对函数的引用而不是返回值 scope.$watch("config.xxx") 将监视 Math.random 的返回值,因为您调用了函数

最简单的方法是使用 $watchCollection documentation但这并不完美

  scope.$watchCollection('config',
    function(config) {
      scope.caught++;
    }
  );

另一种方法是对 $watch'ers 的集合进行编程,它的工作效果稍好一些:

  angular.forEach(scope.config, function(value, key) {
    scope.$watch(function() {
      return scope.config[key];
    }, function(config) {
      scope.caught2++;
    }, true);
  });

关于javascript - angularjs 指令 watch 未在对象函数属性上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26449725/

相关文章:

javascript - Angular - 我应该使用局部变量还是 this.variable

javascript - 比 MD5 更好的方法吗?

javascript - D3.js:如何在 "if..else"语句后更改 xlink:href 图像

javascript - 如何判断页面中是否显示了 HTML 控件?

javascript - 当模型中存在点时, Angular 验证不起作用

javascript - 如何在 TypeScript 中使用 Angularjs

javascript - FirebaseError : Expected type 'Tc' , 但它是:自定义 Ac 对象

javascript - IE 8 自动关闭 &lt;header&gt; 标签

javascript - 刷新页面图像后,AngularJS 的 View 中没有显示?

javascript - 为什么跨 Controller 共享数据在 AngularJS 中不起作用