In AngularJS, $rootScope
is a built-in object that acts as the top-level scope of the application. It is available throughout the app and can be used as a global state store to share data between different controllers, directives, and services.
1. Understanding $rootScope
as a Global Store
Since $rootScope
is available in all controllers and components, it can be used to:
- Store global application state (e.g., user authentication status, themes, language settings).
- Share data between controllers without using services.
- Broadcast events across different components.
2. Storing Global Variables in $rootScope
You can store variables inside $rootScope
and access them anywhere in your AngularJS application.
Example
app.run(function($rootScope) {
$rootScope.appTitle = "My AngularJS App";
});
Accessing in HTML
<h1>{{ appTitle }}</h1>
Accessing in Controllers
app.controller('MainController', function($scope, $rootScope) {
console.log("App Title:", $rootScope.appTitle);
});
This allows all controllers and views to access the appTitle
variable.
3. Using $rootScope
for Global Authentication State
A common use case for $rootScope
is storing user authentication status.
Example: Setting Authentication State
app.run(function($rootScope) {
$rootScope.isAuthenticated = false;
});
Logging In and Updating $rootScope
app.controller('AuthController', function($scope, $rootScope) {
$scope.login = function() {
// Simulate authentication
$rootScope.isAuthenticated = true;
};
$scope.logout = function() {
$rootScope.isAuthenticated = false;
};
});
Using in Views
<p ng-show="isAuthenticated">Welcome, User!</p>
<button ng-click="login()">Login</button>
<button ng-click="logout()">Logout</button>
🔹 This ensures that login state is accessible globally.
4. Sharing Data Between Controllers
Since $rootScope
is accessible everywhere, it can be used to share data between different controllers.
Example
app.controller('ControllerA', function($scope, $rootScope) {
$rootScope.sharedData = "Data from Controller A";
});
app.controller('ControllerB', function($scope, $rootScope) {
console.log("Received:", $rootScope.sharedData);
});
🔹 Both controllers can access the same sharedData
without services.
5. Broadcasting Events with $rootScope
$rootScope
allows event-based communication between different components using:
$broadcast()
– Sends an event downward to child scopes.$emit()
– Sends an event upward to parent scopes.$on()
– Listens for events.
Example: Sending Data Using $broadcast()
app.controller('SenderController', function($scope, $rootScope) {
$scope.sendMessage = function() {
$rootScope.$broadcast('customEvent', { message: "Hello from Sender!" });
};
});
Example: Receiving Data Using $on()
app.controller('ReceiverController', function($scope, $rootScope) {
$scope.$on('customEvent', function(event, data) {
console.log("Received message:", data.message);
});
});
Triggering Event in HTML
<button ng-click="sendMessage()">Send Message</button>
This allows inter-controller communication without direct dependencies.
6. Using $rootScope
as a Global Store with Watchers
You can use $watch
to track changes in $rootScope
.
Example
app.controller('WatcherController', function($scope, $rootScope) {
$scope.$watch(function() {
return $rootScope.globalCount;
}, function(newValue, oldValue) {
console.log("Global count changed:", newValue);
});
});
Updating Global Count
$rootScope.globalCount = 10;
Whenever globalCount
changes, the watcher updates the value.
7. Resetting Global State
When using $rootScope
for global data, it’s important to reset the state when necessary (e.g., after logout).
Example
$rootScope.user = null;
This ensures that old data is cleared out when a user logs out or the app resets.
8. Best Practices for Using $rootScope
as a Global Store
While $rootScope
is powerful, excessive use can lead to performance issues and debugging difficulties. Here are some best practices:
Use $rootScope
Only for Truly Global Data
- Good use cases: User authentication, theme settings, language preferences.
- Avoid storing large datasets.
Prefer Services for Complex State Management
Instead of storing everything in $rootScope
, use an AngularJS service.
Example: Using a Service Instead
app.factory('AuthService', function() {
var user = null;
return {
setUser: function(u) { user = u; },
getUser: function() { return user; }
};
});
This avoids polluting $rootScope
and makes code modular.
Unregister Listeners to Prevent Memory Leaks
If you use $on()
, remove event listeners when controllers are destroyed.
var eventListener = $rootScope.$on('customEvent', function(event, data) {
console.log("Event received:", data);
});
// Remove event listener on destroy
$scope.$on('$destroy', function() {
eventListener();
});
Limit Direct Modifications to $rootScope
Instead of modifying $rootScope
directly, wrap updates inside functions.
$rootScope.setTheme = function(theme) {
$rootScope.currentTheme = theme;
};