213

How would one watch/trigger an event on a route change?

Zanon
  • 29,231
  • 20
  • 113
  • 126
Robert Christian
  • 18,218
  • 20
  • 74
  • 89

6 Answers6

335

Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.

$scope.$on('$routeChangeStart', function($event, next, current) { 
   // ... you could trigger something here ...
 });

The following events are also available (their callback functions take different arguments):

  • $routeChangeSuccess
  • $routeChangeError
  • $routeUpdate - if reloadOnSearch property has been set to false

See the $route docs.

There are two other undocumented events:

  • $locationChangeStart
  • $locationChangeSuccess

See What's the difference between $locationChangeSuccess and $locationChangeStart?

Parzh from Ukraine
  • 7,999
  • 3
  • 34
  • 65
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 39
    You also need to inject "$route" somewhere or these events never fire. – Kevin Beal Oct 01 '13 at 17:41
  • 20
    `$locationChangeStart` and `$locationChangeSuccess` are now documented! http://docs.angularjs.org/api/ng.$location – J.P. Dec 13 '13 at 09:38
  • 2
    @KevinBeal thank you, thank you, *thank you*. I was going bananas trying to work out why these events didn't fire. – Dan F Mar 18 '14 at 01:23
  • 4
    Just a note for everyone using $state, instead of $route. In that case you need to inject $state and use $stateChangeStart. – tomazahlin Jul 31 '14 at 16:25
  • 7
    It's `$rootScope.$on("$routeChangeStart", function (event, next, current) {` now. – jmbmage Aug 28 '14 at 17:21
  • 2
    what's the difference between $locationChangeSuccess and $routeChangeSuccess – OMGPOP Jun 28 '15 at 06:17
  • This is ok, works perfect, but, I have problems when the URL is changed by the next and previous actions fo the browser... Works perfect when I use href or any location thing on my angular app, but crash with navigator actions.. any suggest? – cmarrero01 Apr 06 '17 at 16:16
  • Not sure how you are putting this code. Is this in a controller? How are you injecting $scope into your method? – Coded Container Apr 21 '17 at 16:04
  • thanks @J.P.tenBerge `$locationChangeStart` and `$locationChangeSuccess` worked for me on angularjs 1.4.6 – asotog Apr 22 '22 at 03:28
30

If you don't want to place the watch inside a specific controller, you can add the watch for the whole aplication in Angular app run()

var myApp = angular.module('myApp', []);

myApp.run(function($rootScope) {
    $rootScope.$on("$locationChangeStart", function(event, next, current) { 
        // handle route changes     
    });
});
Zanon
  • 29,231
  • 20
  • 113
  • 126
  • 1
    I love it when I come across an answer like this and find something I didn't know about like .run() although this is not where I needed the event listener in my particular use case, it is very useful to me. Thanks Zanon! – Paul J Nov 08 '16 at 17:50
  • i am learning angular. so i need to know what kind of info we can get from event, next, current argument ? – Monojit Sarkar May 10 '17 at 20:27
11
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //..do something
  //event.stopPropagation();  //if you don't want event to bubble up 
});
honkskillet
  • 3,007
  • 6
  • 31
  • 47
2
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });
Reamon S.
  • 318
  • 3
  • 8
0

For some reason the suggested solutions did not work for me using $routeChangeStart event

If you run into the same problem, try:

$scope.$on('$stateChangeStart', function(evt, toState, toParams, fromState, fromParams) { 
   // ... you could trigger something here ...
 });

In my configuration I'm using @ui-router/angularjs (a.k.a angular-ui-router) from node package manager (a.k.a npm)

Noy Oliel
  • 1,430
  • 3
  • 13
  • 26
-1

This is for the total beginner... like me:

HTML:

  <ul>
    <li>
      <a href="#"> Home </a>
    </li>
    <li>
      <a href="#Info"> Info </a>
    </li>
  </ul>

  <div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-view>

    </div>
  </div>

Angular:

//Create App
var app = angular.module("myApp", ["ngRoute"]);

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Home information</p>"
      })
      .when("/Info", {
        template: "<p>Basic information</p>"
        //templateUrl: "/content/views/Info.html"
      });
});

//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
  $scope.location = $location.path();
  $rootScope.$on('$routeChangeStart', function () {
    console.log("routeChangeStart");
   //Place code here:....
   });
});

Hope this helps a total beginner like me. Here is the full working sample:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script>
</head>
<body>
  <ul>
    <li>
      <a href="#"> Home </a>
    </li>
    <li>
      <a href="#Info"> Info </a>
    </li>
  </ul>

  <div ng-app="myApp" ng-controller="MainCtrl">
    <div ng-view>

    </div>
  </div>
  <script>
//Create App
var app = angular.module("myApp", ["ngRoute"]);

//Configure routes
app.config(function ($routeProvider) {
    $routeProvider
      .otherwise({ template: "<p>Coming soon</p>" })
      .when("/", {
        template: "<p>Home information</p>"
      })
      .when("/Info", {
        template: "<p>Basic information</p>"
        //templateUrl: "/content/views/Info.html"
      });
});

//Controller
app.controller('MainCtrl', function ($scope, $rootScope, $location) {
  $scope.location = $location.path();
  $rootScope.$on('$routeChangeStart', function () {
    console.log("routeChangeStart");
   //Place code here:....
   });
});
  </script>
</body>
</html>
Darrel K.
  • 1,611
  • 18
  • 28