How to detect a route change in AngularJS ?
Approach: To detect route change at any moment in AngularJS this can be achieved by using $on() method. The $on() method is an event handler, the event which will handle $routeChangeSuccess which gets triggered when route/view change is done.
Syntax:
$rootScope.$on('$routeChangeSuccess', function () {
Content...
});
Example: Here, we are displaying “route changed” in the console window whenever there is any route change. Inside the $on() method, we console route changed. Hence, In this way whenever route change occurs, it triggers $routeChangeSuccess handled by $on() event handler and then “route changed” is displayed in the console window.
Below is the implementation of the above approach:
<!DOCTYPE html><html> <head> <title>Angular JS Route Change</title> <script src = <script src = </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <div> <p><a href = "#viewLink1">Link 1</a></p> <p><a href = "#viewLink2">Link 2</a></p> <div ng-app = "mainApp" ng-controller = "GFGController"> <div ng-view></div> </div> <script> var mainApp = angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/viewLink1', { template: "<p> This is Link 1 </p>" }) .when('/viewLink2', { template: "<p> This is Link 2 </p>" }) .otherwise({ redirectTo: '/viewLink1' }); }]); mainApp.controller( 'GFGController', function($scope, $location, $rootScope) { $rootScope.$on('$routeChangeSuccess', function () { console.log("route changed"); }); }); </script> </body></html> |
Output:
As we change the link, the $routeChangeSuccess event gets triggered and thus display route changed in the console window.


