If you only want to know the conclusion:
$scope. $watch ($rootScope. Xxx,function (newval,oldval) {
//do something
})
Someone immediately asks why not:
$rootScope. $watch ("xxx", function (newval,oldval) {
//do something
})
From one of my recent bugs, why use the first method.
Logic as pictured, I used the $rootScope. $watch in the beginning. Because the Angularjs on the $rootScope watch once registered globally valid. And my global variable happens to be order information, which means that different controller have changes to him, and every change triggers $rootScope. $watch into other controller. You can take a look at the $broadcast on the $rootScope to go global.
In fact, this is not the only way to check the angular source code is not hard to find watch method source codes are as follows:
return function Deregisterwatch () {
if (Arrayremove (array, watcher) >= 0) {
incrementwatcherscount (scope,-1 );
}
Lastdirtywatch = null;
This code tells us that it is possible to manually clean the watch. For example:
var watcher = $rootScope. $watch ("xxx", function () {});
Manual removal of watcher
watcher ();
Still very simple, right, the above method can also be used for scope of watch.
When studying here, I feel a little bit of a problem, so will I be cleaned up in $scope? So shout, continue to turn source, I found the following code in $destroy method:
Disable listeners, Watchers and Apply/digest methods this. $destroy = this. $digest = this. $apply = this.
$evalAsync = this. $applyAsync = NoOp;
this. $on = this. $watch = this. $watchGroup = function () {return
noop;
};
this.$ $listeners = {};
The above code is introduced in this article to the ANGULARJS global variable by the scope of the correct posture monitoring, I hope everyone has helped, this article is not good to write a lot of heroes please advice.