Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I ignore the initial load when watching model changes in AngularJS?

The first time the listener is called, the old value and the new value will be identical. So just do this:

$scope.$watch('fieldcontainer', function(newValue, oldValue) {
  if (newValue !== oldValue) {
    // do whatever you were going to do
  }
});

This is actually the way the Angular docs recommend handling it:

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


set a flag just before the initial load,

var initializing = true

and then when the first $watch fires, do

$scope.$watch('fieldcontainer', function() {
  if (initializing) {
    $timeout(function() { initializing = false; });
  } else {
    // do whatever you were going to do
  }
});

The flag will be tear down just at the end of the current digest cycle, so next change won't be blocked.


I realize this question has been answered, however I have a suggestion:

$scope.$watch('fieldcontainer', function (new_fieldcontainer, old_fieldcontainer) {
    if (typeof old_fieldcontainer === 'undefined') return;

    // Other code for handling changed object here.
});

Using flags works but has a bit of a code smell to it don't you think?


During initial loading of current values old value field is undefined. So the example below helps you for excluding initial loadings.

$scope.$watch('fieldcontainer', 
  function(newValue, oldValue) {
    if (newValue && oldValue && newValue != oldValue) {
      // here what to do
    }
  }), true;

Just valid the state of the new val:

$scope.$watch('fieldcontainer',function(newVal) {
      if(angular.isDefined(newVal)){
          //Do something
      }
});