0

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?

2 Answers 2

1

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
  }
};
Sign up to request clarification or add additional context in comments.

Comments

1

You could simply test if view is about to be set for the first time (declared) or is about to be changed (by the select) by testing the params :

$scope.$watch('view'), function(newVal, oldVal) {
  if (oldVal && oldVal != newVal) {
    console.log(1)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.