Open In App
Related Articles

How to detect a route change in AngularJS ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In this article, we will see how to detect a route change in AngularJS. In order to detect route change at any moment in AngularJS, this can be achieved by using the $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...
});

Approach: 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.

Example: This example describes the process to detect a route change in AngularJS.

HTML

<!DOCTYPE html>
<html>
  
<head>
    <title>Angular JS Route Change</title>
    <script src=
    </script>
    <script src=
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <h3>Detecting the route change in AngularJS </h3>
    <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>
    </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 displays route changes in the console window.

 



Last Updated : 06 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads