Home >Web Front-end >JS Tutorial >The correct way for Angularjs global variables to be monitored by scope_AngularJS

The correct way for Angularjs global variables to be monitored by scope_AngularJS

WBOY
WBOYOriginal
2016-05-16 15:16:051346browse

If you just want to know the conclusion:

$scope.$watch($rootScope.xxx,function(newVal,oldVal){
//do something
})

Someone immediately asked why not:

$rootScope.$watch("xxx",function(newVal,oldVal){
//do something
})

Let me tell you why I should use the first method from a recent bug I encountered.

The logic is as shown in the figure. At the beginning, I used the writing method of $rootScope.$watch. Because angularjs's watch on $rootScope is globally valid once registered. And my global variable happens to be order information, which means that different controllers have changes to it, and every change will trigger $rootScope.$watch to enter other controllers. By analogy, $broadcast on $rootScope will start globally.

Actually, this is not the only way. It is not difficult to find the watch method source code by checking the angular source code, including the following code:

return function deregisterWatch() {
if (arrayRemove(array, watcher) >= 0) {
incrementWatchersCount(scope, -1);
}
lastDirtyWatch = null;
};

This code tells us that manually cleaning watch is feasible. For example:

var watcher = $rootScope.$watch("xxx",function(){});
//手动清除 watcher 
watcher();

It’s still very simple, right? The above method can also be used for watches on scope.

When I researched this point, I felt there was a problem. Will my $scope be cleared? So, continue to look through the source code, I found the following code in the $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 the correct posture for Angularjs global variables to be monitored by the scope introduced in this article. I hope it will be helpful to you. If this article is not well written, please give me some advice.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn