有没有办法订阅多个对象上的事件使用 $watch
例如
$scope.$watch('item1, item2', function () { });
有没有办法订阅多个对象上的事件使用 $watch
例如
$scope.$watch('item1, item2', function () { });
从 AngularJS 1.3 开始,有一个新方法被称为$watchGroup观察一组表达式。
$scope.foo = 'foo';
$scope.bar = 'bar';
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
  // newValues array contains the current values of the watch expressions
  // with the indexes matching those of the watchExpression array
  // i.e.
  // newValues[0] -> $scope.foo 
  // and 
  // newValues[1] -> $scope.bar 
});
$watch 第一个参数也可以是一个函数。
$scope.$watch(function watchBothItems() {
  return itemsCombinedValue();
}, function whenItemsChange() {
  //stuff
});
如果您的两个组合值很简单,则第一个参数通常只是一个角度表达式。例如,名字和姓氏:
$scope.$watch('firstName + lastName', function() {
  //stuff
});
这是一个与实际工作的原始伪代码非常相似的解决方案:
$scope.$watch('[item1, item2] | json', function () { });
编辑:好的,我认为这更好:
$scope.$watch('[item1, item2]', function () { }, true);
基本上我们跳过了 json 步骤,这开始看起来很愚蠢,但没有它就行不通。他们的关键是经常被省略的第三个参数,它打开对象相等而不是引用相等。然后我们创建的数组对象之间的比较实际上是正确的。
您可以使用 $watchGroup 中的函数来选择范围内对象的字段。
        $scope.$watchGroup(
        [function () { return _this.$scope.ViewModel.Monitor1Scale; },   
         function () { return _this.$scope.ViewModel.Monitor2Scale; }],  
         function (newVal, oldVal, scope) 
         {
             if (newVal != oldVal) {
                 _this.updateMonitorScales();
             }
         });