是否有一种方法可以使用$watch订阅多个对象上的事件

E.g.

$scope.$watch('item1, item2', function () { });

当前回答

如何:

scope.$watch(function() { 
   return { 
      a: thing-one, 
      b: thing-two, 
      c: red-fish, 
      d: blue-fish 
   }; 
}, listener...);

其他回答

这里有一个解决方案非常类似于你原来的伪代码,实际上是有效的:

$scope.$watch('[item1, item2] | json', function () { });

编辑:好吧,我觉得这个更好:

$scope.$watch('[item1, item2]', function () { }, true);

基本上,我们跳过了json步骤,这一开始看起来很愚蠢,但没有它就无法工作。关键是经常被忽略的第三个参数,它开启对象相等而不是引用相等。然后,我们创建的数组对象之间的比较实际上是正确的。

如何:

scope.$watch(function() { 
   return { 
      a: thing-one, 
      b: thing-two, 
      c: red-fish, 
      d: blue-fish 
   }; 
}, listener...);

Angular在1.3版引入了$watchGroup,用它我们可以用一个$watchGroup块来监视多个变量 $watchGroup将数组作为第一个参数,我们可以在其中包含所有要观察的变量。

$scope.$watchGroup(['var1','var2'],function(newVals,oldVals){
   console.log("new value of var1 = " newVals[0]);
   console.log("new value of var2 = " newVals[1]);
   console.log("old value of var1 = " oldVals[0]);
   console.log("old value of var2 = " oldVals[1]);
});

从AngularJS 1.1.4开始,你可以使用$watchCollection:

$scope.$watchCollection('[item1, item2]', function(newValues, oldValues){
    // do stuff here
    // newValues and oldValues contain the new and respectively old value
    // of the observed collection array
});

这里是Plunker的例子

文件在这里

您可以使用$watchGroup中的函数来选择范围内对象的字段。

        $scope.$watchGroup(
        [function () { return _this.$scope.ViewModel.Monitor1Scale; },   
         function () { return _this.$scope.ViewModel.Monitor2Scale; }],  
         function (newVal, oldVal, scope) 
         {
             if (newVal != oldVal) {
                 _this.updateMonitorScales();
             }
         });