admin管理员组文章数量:1387324
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
本文标签: javascriptAngular scopewatch newValoldValStack Overflow
版权声明:本文标题:javascript - Angular $scope.$watch newVal !== oldVal - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744490209a2608687.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论