How to $watch more than one collection in Angular?

2019-08-01 09:30发布

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.

$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. I would like to combine two watches in one, something like this:

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

How can I do this with Angular?

2条回答
贪生不怕死
2楼-- · 2019-08-01 09:37

Use $scope. $watch('a+b', change). You can add any number of variable to watch

查看更多
小情绪 Triste *
3楼-- · 2019-08-01 09:40

There is something called watchGroup which you can use for this purpose, But unfortunately is is mostly useless as it does only shallow watch.

You could use the watcher function to return your object

$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);
});
查看更多
登录 后发表回答