Correct posture for Angularjs global variables to be scoped

  • 2020-12-16 05:50:03
  • OfStack

If you just want to know the conclusion:


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

Immediately someone asked why not:


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

Here's why I used the first approach from my last bug.

The logic is shown in the figure. At the beginning of 1, I used the writing method of $rootScope. $watch. Because angularjs registers globally as soon as watch 1 on $rootScope. My global variable happens to be the order information, that is to say, different controller have changes to it, each change will trigger $rootScope.$watch goes to other controller. The analogy is that $broadcast on $rootScope under 1 is global.

In fact, this is not the only way, looking at 1 angular source code is not difficult to find watch method source code without the following code:


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

This code tells us that it is possible to clean watch manually. Such as:


var watcher = $rootScope.$watch("xxx",function(){});
// Manually remove  watcher 
watcher();

Simple enough. The same goes for watch on scope.

When I got here, I thought there was a problem. Will My $scope be cleaned up? So call, continue to open 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 of Angularjs global variable monitored by scope, I hope you can help, this article is not good to write, please give advice.


Related articles: