gsk
gsk

Reputation: 2379

clear scope variable inside its $watch function?

I want to clear $scope variable inside $watch function. but it is not working. How can I implement this one?

    $scope.$watch('selectedEmployee', function (value) {
     //do some stuffs
     -------
     -------
     -------   
     $scope.selectedEmployee ={};//clearing variable
}

This code is not working.

Upvotes: 0

Views: 470

Answers (1)

Michael Kang
Michael Kang

Reputation: 52837

I agree with the general comments that watching a variable, and then changing the variable inside of its own watch handler is rarely a good idea. However, there could be some obscure use cases where one would want to do this.

To avoid an infinite digest loop, you should ensure that the reference is preserved, and stable:

var empty = {};
$scope.$watch('selectedEmployee', function (value) {
     if (value != empty) {
         //do some stuffs
         -------
         -------
         -------   
        $scope.selectedEmployee = empty;//clearing variable
     }     
 }

This should work because the value will stablise to an empty reference when the digest loop runs.

However, this approach is still potentially problematic - you should have a "dot" in your scope model to ensure that it resolves to the right reference. Otherwise, when you overwrite the scope reference with an assignment, you could create a copy of the variable on the immediate scope that is a copy of the original scope variable.

Here is an improved example:

var empty = {};
$scope.my = { selectedEmployee = {} };
$scope.$watch('my.selectedEmployee', function (value) {
     if (value != empty) {
         //do some stuffs
         -------
         -------
         -------   
        $scope.my.selectedEmployee = empty;//clearing variable
     }     
 }

Upvotes: 1

Related Questions