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

E.g.

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

当前回答

一个稍微安全一点的组合值的解决方案可能是使用下面的$watch函数:

function() { return angular.toJson([item1, item2]) }

or

$scope.$watch(
  function() {
    return angular.toJson([item1, item2]);
  },
  function() {
    // Stuff to do after either value changes
  });

其他回答

$watch的第一个参数也可以是一个函数。

$scope.$watch(function watchBothItems() {
  return itemsCombinedValue();
}, function whenItemsChange() {
  //stuff
});

如果你的两个组合值很简单,第一个参数通常只是一个角度表达式。例如,firstName和lastName:

$scope.$watch('firstName + lastName', function() {
  //stuff
});
$scope.$watch('age + name', function () {
  //called when name or age changed
});

在这里,当年龄和名称值都被改变时,函数将被调用。

$watch的第一个参数可以是角表达式或函数。请参阅有关$scope.$watch的文档。它包含了很多关于$watch方法如何工作的有用信息:何时调用watchExpression, angular如何比较结果等。

从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的例子

文件在这里

如何:

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