简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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