Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - How to use a $watchGroup with object equality or deep-watch the properties in the group?

I want a directive to re-render HTML whenever three scope variables have changed. The first two are just integers, the third is an array.

We have $watchGroup to watch several variables, we have $watch with objectEquality as a third parameter, and we have $watchCollection which is like $watch, but with objectEquality implied.

Is there a way to write a $watch similar to this?

$scope.$watchGroup(['number1', 'number2', 'myArray'], callback, true); // true for objectEquality
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well it seems like watchGroup does not support a deep watch. So probably you can do a hack, by registering an anonymous deep watcher with array of values being passed in from the watch function.

$scope.$watch(function(){
     return ['number1','number2','myArray'].map(angular.bind($scope, $scope.$eval));
  }, function(newV){
      console.log(newV);
  },true);

Demo

or just add this function as utility function on the rootScope and access it from any inherited scopes.

.run(function($rootScope){
  $rootScope.deepWatchGroup = function(exp, callback){
    if(!angular.isArray(exp) || !thisScope.$watch) return; //Or log some error if array is not passed in or the context is not really a scope object

   var thisScope = this, //get scope
        evalFunc = angular.bind(thisScope, thisScope.$eval); //and a bound eval func

     thisScope.$watch(function(){
        return exp.map(evalFunc); //return array of evaluated values
     }, callback,true);
   }
});

and from your controller do:

$scope.deepWatchGroup(['number1','number2','myArray'],function(newV){
  console.log(newV);
});

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...