您可以收听发出的多个事件
$routeservice。这些事件是:
$routeChangeStart
$routeChangeSuccess
$routeChangeError
- 和,
$routeUpdate
(我鼓励阅读链接提供的文档,以获取每个文件的描述。)
此时,您可以在一个
$scope控制器或指令之一上侦听一个或所有这些事件,或者通过注入
$rootScope到您的
angular.module().run()函数或另一个服务/工厂中。
例如,作为您提供的代码的附录:
reportFormsApp.config(function ($routeProvider) { $routeProvider .when("/Reporting", { templateUrl: "ReportForm/rfTemplate.html", controller: "rfController" }) .when("/Dashboard", { templateUrl: "DashboardForm/dfTemplate.html", controller: "dfController" }) .when("/Analysis", { templateUrl: "AnalysisForm/afTemplate.html", controller: "afController" }) .otherwise({ redirectTo: "/Reporting" })});reportFormsApp.run([ '$rootScope', function($rootScope) { // see what's going on when the route tries to change $rootScope.$on('$routeChangeStart', function(event, next, current) { // next is an object that is the route that we are starting to go to // current is an object that is the route where we are currently var currentPath = current.originalPath; var nextPath = next.originalPath; console.log('Starting to leave %s to go to %s', currentPath, nextPath); }); }]);您还可以访问其余的
$routeProvider对象,例如
current.templateUrl或
next.controller。
有关redirectTo的注意事项: 使用
$routeservice事件有一个对象异常,那就是存在重定向时。在这种情况下,
next.originalPath将是undefined,因为您所拥有的只是
redirectTo您在中定义的属性
otherwise()。您将永远不会看到用户尝试访问的路由。
因此,您可以收听或事件:
$locationservice's
$locationChangeStart``$locationChangeSuccess
reportFormsApp.run([ '$rootScope', function($rootScope) { // see what's going on when the route tries to change $rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) { // both newUrl and oldUrl are strings console.log('Starting to leave %s to go to %s', oldUrl, newUrl); }); }]);如果使用HTML5Mode,则
$locationChange*事件将提供其他两个参数。这些是
newState和
oldState。
总之,侦听
$route*事件可能是调试中提供的对象和定义的最佳选择
$routeProvider。但是,如果您需要查看所有尝试的URL,
$locationChange*则将需要侦听事件。
截至 AngularJS 1.3.9版本



