Optimizing the application using $watch deregistration
Nothing boosts watcher performance quite like destroying the watcher altogether. Should you encounter a scenario where you no longer have a need to watch a model component, invoking watch creation returns a deregistration function that will unbind that watcher when called.
How to do it…
When a watcher is initialized, it will return its deregistration function. You must store this deregistration function until it needs to be invoked. This can be done as follows:
$scope.myObj = {} // watch myObj by reference var deregister = $scope.$watch('myObj', function(newVal, oldVal, scope) { // callback logic }); // prevent additional modifications from invoking the callback deregister();
Tip
JSFiddle: http://jsfiddle.net/msfrisbie/yLhwfvwL/
How it works…
The $watch
destruction will normally be needed when a change in application state causes a watch to no longer be useful while the scope that it is defined inside still exists. When a scope is destroyed...