Zach
Zach

Reputation: 5885

AngularJS: what is the execution order of $watch?

I have a watch function:

scope.$watch('target', function(){
   scope.hasUnsavedChanges = true;
}, true);

Then I change some value:

functiion change(target){
   scope.hasUnsavedChanges = false;
   scope.target.Xxx = '';
   console.log('scope.hasUnsavedChanges = ' + scope.hasUnsavedChanges); 
}

It outputs false. So when the watch function executes? And how to run some code after scope.hasUnsavedChanges becomes true in the above code?

Upvotes: 3

Views: 1518

Answers (1)

Dalorzo
Dalorzo

Reputation: 20014

$watch functions executes after every time $scope.$digests() function is called.

And if you want to execute code after a variable like hasUnsavedChanges become true. Wouldn't it make more sense to make it a function instead and execute all code there like:

scope.setUnsavedChanges = function(){  
  scope.hasUnsavedChanges = true; 
  //the rest of your code goes here
}

scope.$watch('target', function(){
   scope.setUnsavedChanges();
}, true);

Upvotes: 2

Related Questions