11

According to my knowledge when we attach a variable to the scope , watches are applied to it and it is checked every digest cycle. A good rule of thumb is that we should not have more than 2000 variables being watched at a given time.

My question is how do you remove an already present variable from scope. For example $scope.var1=1 say I had to create it for a one time use. Is it possible for me to "delete" it from the scope or will the variable be watched for the life time of the scope ?

EDIT :

From the comments below I understand that you are supposed to remove the watches manually or they get destroyed when the scope gets destroyed. However I am still unclear as to how will you remove watches for variables which are set by directives such as ngModel ?

Kiran Yallabandi
  • 2,544
  • 2
  • 22
  • 25
  • @Roman C Correct me if I'm wrong so the solution suggested in the question is that we remove a reference to the given variable and in essence let the garbage collector do the work ? I did think about it too but I thought their might be a more "angular" way to do it – Kiran Yallabandi Aug 19 '15 at 19:12
  • Simply creating a value on the scope does not create a watch on it... Also, if there is a watch, simply deleting the variable on the scope will not clean up the watch. If concerned about too many watches, consider one-time binding (Angular > 1.3) where applicable. – Patrick Aug 19 '15 at 19:20

1 Answers1

36

You can simply use the delete keyword:

delete $scope.var1;
aghidini
  • 2,855
  • 5
  • 29
  • 32
  • Okay so by using delete keyword we dereference the property from the object. So that should get rid of the corresponding watches and prevents it from being checked in the digest cycle too, is my understanding correct ? – Kiran Yallabandi Aug 19 '15 at 19:19
  • 2
    No -- Deleting the value (if defined) would cause a watch callback to execute since the value is going from defined to deleted/undefined. watches are explicitly set through calling $scope.$watch or implicitly through using a directive that creates a watch (e.g. ngModel). – Patrick Aug 19 '15 at 19:21
  • The property does not exist anymore in the `$scope` object and it is not checked in the digest cycle however the watches are left untouched. If you want to remove watches see [Angular Js Clear $watch](http://stackoverflow.com/questions/14957614/angular-js-clear-watch) – aghidini Aug 19 '15 at 19:23
  • 1
    Okay now I understand how it works, So basically all I have to worry about is removing unnecessary watches from the variables set on the scope in order to keep my application from slowing down, However how can I remove watches for variables for which the watches were set by directives, such as ngModel ? – Kiran Yallabandi Aug 19 '15 at 19:35