Issue
I saw the pattern below many times:
$scope.$watch('full_name', function(newVal, oldVal, scope) {
if(newVal === oldVal) {
return
} else {
}
}
I don't quite understand the if(newVal==oldVal)
branch because it looks useless.. Shouldn't the listener callback function only be called when the watched value is changed? If that is the case, shouldn't newVal
always be different from oldVal
?
If not, does anyone have examples about what can be done in the newVal==oldVal
branch?
Solution
The if (newVal === oldVal)
construct is to skip initialisation. AngularJS documentation states that when you attach the watch, it will call the callback once with undefined, undefined
. To prevent your watch function from mistaking this call for a model change, you can add the if
construct.
After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.
Answered By - Steve Klösters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.