How to watch for a route change in AngularJS?

JavascriptAngularjs

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 https://stackoverflow.com/questions/15006849/angularjs-whats-the-difference-between-locationchangesuccess-and-locationch

Solution 2 - Javascript

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     
    });
});

Solution 3 - Javascript

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //..do something
  //event.stopPropagation();  //if you don't want event to bubble up 
});

Solution 4 - Javascript

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });

Solution 5 - Javascript

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)

Solution 6 - Javascript

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

HTML:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert ChristianView Question on Stackoverflow
Solution 1 - JavascriptMark RajcokView Answer on Stackoverflow
Solution 2 - JavascriptZanonView Answer on Stackoverflow
Solution 3 - JavascripthonkskilletView Answer on Stackoverflow
Solution 4 - JavascriptReamon C. SumapigView Answer on Stackoverflow
Solution 5 - JavascriptNoy OlielView Answer on Stackoverflow
Solution 6 - JavascriptDarrel K.View Answer on Stackoverflow