How to $watch more than one collection in Angular?

左心房为你撑大大i 提交于 2019-12-11 09:38:47

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/25956768/how-to-watch-more-than-one-collection-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!