Organizational Research By

Surprising Reserch Topic

angular scope watch newval oldval


angular scope watch newval oldval  using -'javascript,angularjs'

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?
    

asked Oct 13, 2015 by gauravsinghal83
0 votes
2 views



Related Hot Questions

3 Answers

0 votes

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.

answered Oct 13, 2015 by kinnari
0 votes

This function is watching the scope model value of $scope.calculator.value

If it changes, it fires the updateCalculation() function. If the value is the same, it just returns false.

answered Oct 13, 2015 by tejas lakhani
0 votes

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.

answered Oct 13, 2015 by kinnari

...