$rootScope
is considered global, while $scope
is considered local within AngularJS. When a Controller is assigned to a page, a $scope
variable can be used because it binds to that specific controller. However, when the value needs to be shared across other controllers or services, $rootScope
is typically utilized (although there are alternative methods for sharing values as well).
Exploring AngularJS Scope Life-Cycle
A property assigned with $scope
is limited to usage within the controller where it is defined, whereas a property assigned with $rootScope
can be accessed from anywhere in the application.
If you require a variable that can be accessed in multiple controllers throughout your application, then utilizing $rootScope
is recommended.
$rootScope
serves its purpose, but caution should be exercised
In Angular, scopes form a hierarchy, inheriting properties from a root scope at the top of the tree. Normally, this hierarchical structure goes unnoticed as most views have their own controller and corresponding scope.
However, there may be scenarios where certain data needs to be globally accessible within the application. In such cases, $rootScope
can be injected with values just like any other scope. Since scopes inherit from the root scope, these global values will be available in directives like ng-show
, similar to values on local $scope
.
Nevertheless, excessive use of global state, including $rootScope
, is discouraged. It is advisable to use $rootScope
sparingly, treating it similar to global variables in traditional programming languages. Avoid using it for executable code, focusing more on storing data instead. Functions intended for $rootScope
placement are better off in injectable services for improved testing and maintainability.
On the flip side, creating services solely for storing and retrieving small bits of data is also not recommended.
— AngularJS Docs Miscellaneous - FAQ