简体   繁体   中英

How to watch for a route change in AngularJS?

如何观察/触发路线变化上的事件?

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 - ifreloadOnSearch 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?

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     
    });
});
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //..do something
  //event.stopPropagation();  //if you don't want event to bubble up 
});
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });

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 (aka angular-ui-router) from node package manager (aka npm)

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM