The correct posture of Angularjs global variables being monitored by scope, and angularjs global variables
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})
From a recent bug, I explained why the first method is used.
Logic. At first I used $ rootScope. $ watch. Because angularjs watch on $ rootScope is valid globally once registered. My global variable happens to be the order information. That is to say, different controllers have changes to it. Every change triggers $ rootScope. $ watch to enter another controller. Let's look at $ broadcast on $ rootScope.
In fact, this is not the only method. It is not difficult to find the 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 manual cleaning of watch is feasible. For example:
Var watcher = $ rootScope. $ watch ("xxx", function () {}); // manually clear watcher ();
It's easy, right? The above method can also be used for the watch on the scope.
When I found this, I felt a problem. Will I be cleaned up in $ scope? As a result, call and continue to the source code. I found the following code in the $ destroy method:
// Disable listeners, watchers and apply/digest methodsthis.$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 listened to by scope. I hope you can help. If this article is not well written, please kindly advise.
Articles you may be interested in:
- AngularJS Scope
- Details about the scope in AngularJS