简体   繁体   English

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

[英]How to $watch more than one collection in Angular?

I have two arrays in my application I would like to observe changes: 我的应用程序中有两个数组,我想观察一下变化:

$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
}

I have to call the changed() function when a or b have been changed. ab被更改时,我必须调用changed()函数。

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

The changed() callback will be triggered twice if I have changes in a and b as well as on init step. 如果我在ab以及init步骤中进行a更改,则change changed()回调将被触发两次。 I would like to combine two watches in one, something like this: 我想将两块手表合而为一,就像这样:

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

How can I do this with Angular? 如何使用Angular做到这一点?

There is something called watchGroup which you can use for this purpose, But unfortunately is is mostly useless as it does only shallow watch. 有一个名为watchGroup东西可以用于此目的,但是不幸的是它几乎没有用,因为它仅用于浅表。

You could use the watcher function to return your object 您可以使用watcher函数返回对象

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

You could instead create a custom watcher for your convenience as i had mentioned in another answer and do something like this. 您可以为方便起见创建一个自定义观察程序,就像我在另一个答案中提到的那样,然后执行类似的操作。

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

Use $scope. $watch('a+b', change) 使用$scope. $watch('a+b', change) $scope. $watch('a+b', change) . $scope. $watch('a+b', change) You can add any number of variable to watch 您可以添加任意数量的变量来观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM