How to destroy a $ scope. $ watch?

7

I have the following $scope.$watch in the controller of a directive that 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 indicated above by a comment, I would like $watch to be turned off / destroyed, since I will no longer need to detect changes in the active value.

Is there any way to destroy / disable an Angular watch?

    
asked by anonymous 18.11.2016 / 12:02

2 answers

5

I particularly find it strange how to do this, and I do not know if I have another. However, you simply declare a variable for whatch and "call it" when you no longer want to observe. Your example would look 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);
    }
});

For more explanation, this question has more explanations.

    
18.11.2016 / 12:14
6

All scope monitoring functions return a deregistration function:

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

To unregister a listener , simply call your deregistration function:

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

Source: Angular DocumentationJS, $ rootScope.Scope

    
18.11.2016 / 17:24