当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - 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?

网友答案:

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
  }
};
网友答案:

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)
  }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: