How to destroy a $Scope. $watch?

Asked

Viewed 293 times

7

I have the following $scope.$watch in the controller of a directive I created:

var interval;

$scope.$watch('active', function () {

    if ($scope.active == true) {

        interval = $interval(function () {

            if ($scope.current >= $scope.to) {

                // Quero destruir o Watch aqui.

                return $interval.cancel(interval);
            }

            $scope.current += amounth;

        }, 10);

    }
});

When the value falls within the condition stated above by a comment, I would like the $watch turned off/destroyed as I will no longer need to detect changes in the value active.

Is there any way to destroy/disable a watch in Angular?

  • 2

    In your watch statement you assign it to a variable. When you want to destroy it you execute the function that will be in the variable: var meuWatch = $scope.$watch('active', function ()...; meuWatch();

  • This works just like Jquery settimeout?

  • setTimeout it’s not jQuery, it’s Javascript. And no, it’s not the same.

2 answers

6

All scope monitoring functions return a deregistration function:

  • $applyAsync
  • $on
  • $watch
  • $watchGroup
  • $watchCollection

To deregister a Listener, simply call your deregister function:

var dereg = $scope.$watch('target', function () {}); // Inicia monitoramento
dereg(); // Encerra monitoramento

Source: Documentation Angularjs, $rootScope.Scope

5


I particularly found it a little strange how to do this, and I don’t know if you have another one. However, just declare a variable for the Whatch and "call you" when you no longer wish to observe. Your example would be something like this:

var interval;
var watchAtivo = $scope.$watch('active', function () {
    if ($scope.active == true) {
        interval = $interval(function () {
            if ($scope.current >= $scope.to) {
                // Destroi o watch aqui
                watchAtivo ();
                return $interval.cancel(interval);
            }
            $scope.current += amounth;
        }, 10);
    }
});

If you want more explanation on the subject, this question has more explanations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.