如何$在Angular中观看多个收藏

How to $watch more than one collection in Angular?

本文关键字:收藏 中观 Angular 如何      更新时间:2023-09-26

我的应用程序中有两个数组,我想观察变化:

$scope.a = [{id: 1, text: 'test a - 1'}, ...];
$scope.b = [{id: 1, text: 'test b - 1'}, ...];
function changed(){
  // notify application about changes in a or b
}

ab发生更改时,我必须调用changed()函数。

$scope.$watchCollection('a', changed);
$scope.$watchCollection('b', changed);

如果我在ab以及初始化步骤中有更改,changed()回调将被触发两次。我想把两块手表合为一块,大概是这样的:

$scope.$watchCollection('a, b', changed);

如何使用Angular完成此操作?

有一种叫做watchGroup的东西可以用于此目的,但不幸的是,它大多是无用的,因为它只做浅表。

你可以使用观察者函数返回你的对象

$scope.$watch(function(){ //Or even try this with watchCollection
     return ['a','b'].map(angular.bind($scope, $scope.$eval));
  }, function(newV){
      console.log(newV);
  },true);

相反,正如我在另一个答案中提到的那样,您可以创建一个自定义观察程序,并执行类似的操作。

$scope.deepWatchGroup(['a','b'],function(newV){
  console.log(newV);
});

使用$scope. $watch('a+b', change)。您可以添加任意数量的变量来观看