简体   繁体   English

如何观察 AngularJS 中的路线变化?

[英]How to watch for a route change in AngularJS?

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

Note : This is a proper answer for a legacy version of AngularJS.注意:这是对旧版 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 $routeChangeSuccess
  • $routeChangeError $routeChangeError
  • $routeUpdate - ifreloadOnSearch property has been set to false $routeUpdate - 如果reloadOnSearch属性已设置为 false

See the $route docs.请参阅$route文档。

There are two other undocumented events:还有另外两个未记录的事件:

  • $locationChangeStart $locationChangeStart
  • $locationChangeSuccess $locationChangeSuccess

See What's the difference between $locationChangeSuccess and $locationChangeStart?请参阅$locationChangeSuccess 和 $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()如果您不想将手表放在特定的控制器中,您可以在 Angular 应用程序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出于某种原因,建议的解决方案对我使用$routeChangeStart事件不起作用

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)在我的配置中,我使用来自节点包管理器(又名 npm)的 @ui-router/angularjs(又名 angular-ui-router)

This is for the total beginner... like me:这是给初学者的……像我一样:

HTML: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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