![]()
Route guards in AngularJS are used to control the navigation behavior of a user, ensuring that the user is authorized or meets certain conditions before they can navigate to a particular route. AngularJS provides several ways to implement route guards, one of the most common being the use of the $rootScope.$on('$routeChangeStart') event to intercept route changes.
In this guide, we’ll walk through how to use $rootScope.$on('$routeChangeStart') for implementing route guards in AngularJS.
1. What is $rootScope.$on('$routeChangeStart')?
The $rootScope.$on('$routeChangeStart') event in AngularJS is fired when the route is about to change. You can use this event to guard or prevent certain route transitions based on conditions like user authentication, authorization, or other custom logic.
The $routeChangeStart event allows us to:
- Prevent route navigation.
- Redirect the user to another route if a certain condition is not met.
- Perform checks or actions before the route is fully loaded.
2. Setting Up AngularJS with Route Guards
Step 1: Install ngRoute Module
Before we can start using $routeChangeStart, ensure that the ngRoute module is included in your application. This module is essential for setting up routing in AngularJS.
Include the ngRoute script in your index.html:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js"></script>
Step 2: Configure Routes Using $routeProvider
You need to define routes using the $routeProvider to configure the view templates and controllers. The basic setup involves defining several routes with corresponding templates and controllers.
Example:
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.otherwise({
redirectTo: '/home'
});
});
Here, we have two routes, /home and /login, along with their templates and controllers.
3. Implementing Route Guards with $rootScope.$on('$routeChangeStart')
To create a route guard, we can use the $rootScope.$on('$routeChangeStart') event. This will allow us to intercept every route change and apply conditional logic before the route change happens.
Step 3: Implement Route Guard Logic
In this step, we’ll write a route guard that checks whether the user is logged in. If the user is not logged in and tries to access the /home route, we’ll redirect them to the /login route.
Example:
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.otherwise({
redirectTo: '/home'
});
});
app.run(function($rootScope, $location) {
// Simulate user authentication status (true = logged in, false = not logged in)
var isAuthenticated = false;
// Listen to route change events
$rootScope.$on('$routeChangeStart', function(event, next, current) {
// If the user is not logged in and is trying to access the /home route
if (!isAuthenticated && next.templateUrl === 'home.html') {
// Prevent the route change
event.preventDefault();
// Redirect the user to the login page
$location.path('/login');
}
});
});
Explanation:
$rootScope.$on('$routeChangeStart'): This event is fired whenever the route changes.- The event handler receives
event,next, andcurrentas parameters:event: The event object that is fired when the route change starts.next: The route information for the route we are about to navigate to (including the template and controller).current: The route information for the current active route.
- The event handler receives
event.preventDefault(): This is used to stop the route change if a condition is met. In this case, we prevent navigation to/homeif the user is not authenticated.$location.path('/login'): If the user is not authenticated and tries to navigate to/home, we redirect them to the/loginroute using$location.path().
4. Allowing Access After Authentication
If the user successfully logs in, we should update the authentication status (isAuthenticated) and allow them to access the /home route.
Step 4: Implement the Login Logic
In the LoginController, let’s simulate a successful login by updating the isAuthenticated flag.
Example: LoginController.js
app.controller('LoginController', function($scope, $rootScope, $location) {
// Simulate a login attempt
$scope.login = function() {
// Set the authentication flag to true when the user logs in
$rootScope.isAuthenticated = true;
// After successful login, redirect the user to the home page
$location.path('/home');
};
});
Here, when the user clicks the login button, the login() function sets isAuthenticated to true, and then redirects the user to the /home route.
5. Handling Unauthorized Access
If a user tries to access a route they are not authorized to access (such as /home without being authenticated), the route guard will redirect them to the login page. We can show a message or redirect the user based on certain conditions, making the navigation experience more secure.
6. Example of Full Application with Route Guards
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Route Guard Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
<script src="app.js"></script>
<script src="controllers.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
app.js (Main AngularJS Application)
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.otherwise({
redirectTo: '/home'
});
});
app.run(function($rootScope, $location) {
var isAuthenticated = false;
$rootScope.$on('$routeChangeStart', function(event, next) {
if (!isAuthenticated && next.templateUrl === 'home.html') {
event.preventDefault();
$location.path('/login');
}
});
});
controllers.js (Controllers)
app.controller('HomeController', function($scope) {
$scope.message = "Welcome to the Home page!";
});
app.controller('LoginController', function($scope, $rootScope, $location) {
$scope.login = function() {
$rootScope.isAuthenticated = true;
$location.path('/home');
};
});
