Itsik Mauyhas Itsik Mauyhas - 5 months ago 65
AngularJS Question

Angular $watch - execute watch block only once

I have a simple

$watch
on a
dropdown
value :

$scope.view;
$scope.$watch('view', function(){
console.log(1);
// watch block
}


The value is chaining with
ng-model
:

<select ng-model="view" ng-options="x for x in name">
</select>


Due to the
$digest
the value 1 is printed twice, is there a way to tell angular to execute the the
$watch
block only once?

Answer

Simple answer: unregister the watch after the first successful run:

var viewWatch = $scope.$watch('view', function () {
  viewWatch(); // Stops the watch
  console.log(1);       
  //watch block
};

However this may or may not yield the results you want, because sometime the $watch is called upon initialization. You may want to set some conditions:

var viewWatch = $scope.$watch('view', function (currentValue, oldValue) {
  if (currentValue && !oldValue) {
    viewWatch(); // Stops the watch
    console.log(1);       
    //watch block
  }
};