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?

Share Improve this question asked Oct 13, 2015 at 14:30 NLuburićNLuburić 9221 gold badge10 silver badges28 bronze badges 1
  • Not familiar with $watch but isn't it just checking if the value changed? – MinusFour Commented Oct 13, 2015 at 14:34
Add a ment  | 

3 Answers 3

Reset to default 7

The $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.

  1. There is a value on the scope like $scope.calculator.value = 0;
  2. Watch will call with every digest but might be this value is not changed
  3. So match old value with new value and call the method if only there is any change

本文标签: javascriptAngular scopewatch newValoldValStack Overflow