$rootScope
exists, but it can be used for evil
The regions in Angular form a hierarchy that inherits from the root region at the top of the tree. This can usually be ignored, since most views have a controller and therefore scope.
Sometimes there are pieces of data that you want to make global for the entire application. To do this, you can enter $rootScope
and set values ββfor it, as in any other area. Because areas inherited from the root area, these values ββwill be available to expressions attached to directives like ng-show
, just like the values ββon your local $scope
.
Of course, the global state sucks and you should use $rootScope
sparingly , as you (hopefully) use with global variables in any language. In particular, do not use it for code, but only data. If you are tempted to put a function on $rootScope
, it is almost always better to put it in a service that can be inserted where you need it and more easily tested.
Conversely, do not create a service whose sole purpose is to store and return data bits.
- AngularJS Frequently Asked Questions
source share