I've been working on an angular project I inherited and I can't contact the original author. There is this watch expression I'm not sure of and I was wondering if someone could help me understand the code:
$scope.$watch(calculator.value, function(newVal, oldVal) {
if(newVal !== oldVal) {
i = newVal;
updateCalculation();
}
});
What confuses me is this line of code: newVal !== oldVal
. Any idea why one would need such a check?
I've been working on an angular project I inherited and I can't contact the original author. There is this watch expression I'm not sure of and I was wondering if someone could help me understand the code:
$scope.$watch(calculator.value, function(newVal, oldVal) {
if(newVal !== oldVal) {
i = newVal;
updateCalculation();
}
});
What confuses me is this line of code: newVal !== oldVal
. Any idea why one would need such a check?
-
Not familiar with
$watch
but isn't it just checking if the value changed? – MinusFour Commented Oct 13, 2015 at 14:34
3 Answers
Reset to default 7The $watch
method of a scope will always execute the callback at least once. The first time it does the new and old values are the same.
$scope.$watch(calculator.value, function(newVal, oldVal) {
if(newVal === oldVal) {
console.log('First time watcher is executed');
}
if(newVal !== oldVal) {
console.log('Watcher called because values changed.');
}
});
The sample you gave states that it will only execute updateCalculations()
when the values have changed. Not the first time the watcher is called.
The $watch will get called for each turn of the $digest loop even if the value hasn't changed. So I can only assume that updateCalculation() should only be called if the value changed.
- There is a value on the scope like $scope.calculator.value = 0;
- Watch will call with every digest but might be this value is not changed
- So match old value with new value and call the method if only there is any change