简体   繁体   中英

How to make $watch only trigger once?

I added the $watch ; the code inside the $watch throws an error if panodatas is undefined :

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.

How can I do it so that $watch only triggers once and not when panodatas changes in the future?

Try this:

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

scope.$watch returns a deregister function, so if you do it like this:

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

it will deregister as soon as it runs.

You can clear the $watch inside the function -

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

It will be called once and then the watcher will be cleared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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