简体   繁体   English

如何使$ watch只触发一次?

[英]How to make $watch only trigger once?

I added the $watch ; 我加了$watch the code inside the $watch throws an error if panodatas is undefined : 如果undefined panodatas,则$watch的代码将引发错误:

scope.$watch('panodatas', function(newVal) {
   if ('isCreate' in attrs) {
      $('.modal #points').hide()
      $('.modal #points-info').hide()
   }

   if (newVal || 'isCreate' in attrs) {
      scope.x = 0
      scope.y = 0
      scope.points = []

The problem is, the code fires every time panodatas changes. 问题是,每次panodatas更改时,代码都会触发。

How can I do it so that $watch only triggers once and not when panodatas changes in the future? 我该怎么做,以使$watch仅触发一次,而以后在panodatas更改时不会触发?

Try this: 尝试这个:

var unwatch = $scope.$watch('someVar', function() {
   unwatch();
});

scope.$watch returns a deregister function, so if you do it like this: scope.$watch返回一个注销函数,因此,如果您这样做:

var dereg = scope.$watch('panodatas', function(newVal) {
    dereg();
});

it will deregister as soon as it runs. 它会在运行后立即注销。

You can clear the $watch inside the function - 您可以清除函数内的$watch

var listener = $scope.$watch("panodates", function () {
    // ...
    listener(); // Would clear the watch
});

It will be called once and then the watcher will be cleared. 它将被调用一次,然后清除观察者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM