观察多个$scope属性

Watch multiple $scope attributes

本文关键字:scope 属性 观察      更新时间:2023-09-26

有没有办法使用 $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 
});

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
});
此处为普

伦克示例

文档在这里

$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 步骤,这看起来很愚蠢,但没有它它就无法工作。 它们的关键是经常省略的第 3 个参数,它打开对象相等而不是引用相等。 然后,我们创建的数组对象之间的比较实际上可以正常工作。

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

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

为什么不简单地把它包装在forEach里呢?

angular.forEach(['a', 'b', 'c'], function (key) {
  scope.$watch(key, function (v) {
    changed();
  });
});

这与为组合值提供函数的开销大致相同,实际上不必担心值组合

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

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

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

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

怎么样:

scope.$watch(function() { 
   return { 
      a: thing-one, 
      b: thing-two, 
      c: red-fish, 
      d: blue-fish 
   }; 
}, listener...);
$scope.$watch('age + name', function () {
  //called when name or age changed
});

当年龄和名称值都更改时,将调用此处的函数。

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]);
});