2

I have a situation in which I want to monitor a specific variable.

$scope.$watch('action', function() { /* do something */ }

However, I only want to do something if $scope.id didn't change (if $scope.action changes it is possible that $scope.id has changed too.)

The only solution I can think of is

$scope.$watch('action', function() { 
    if(idHasChanhed === false){
        /* do something */ 
    }
    idHasChanged = false;
});
$scope.$watch('id', function() { idHasChanged = true }

However, I was wondering if angular has a better solution than this, and I don't know if this solution will always work ( is the order in which the $watches are executed random !?)

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333

3 Answers3

4

My solution :

$scope.$watch('[action,id]', function() { 
   // called when action or id changed
});

Info : The string concatenation action + id will fail.

EpokK
  • 38,062
  • 9
  • 61
  • 69
  • 1
    Hmm, I've implemented it now and I get the following error: `Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!` It gets triggered all the time without the data changing – Jeanluca Scaljeri Feb 10 '14 at 14:33
  • Turns out that my question is a duplicate of [this](http://stackoverflow.com/questions/16729965/how-to-watch-multiple-variable-change-in-angular) question – Jeanluca Scaljeri Feb 10 '14 at 15:08
0
var action,id;   // variables you need to watch
 $scope.$watch('action + id', function() { 
       // actions
    });
0

$watchGroup This function is introduced in Angular1.3. This works the same as $watch() function except that the first parameter is an array of expressions to watch.

Use $watchGroup

$scope.$watchGroup(['action', 'id'], function(newVal, oldVal) {
    //write your code here
});
murli2308
  • 2,976
  • 4
  • 26
  • 47