如何在路线改变时观察/触发事件?
请注意:这是AngularJS遗留版本的正确答案。更新的版本见这个问题。
$scope.$on('$routeChangeStart', function($event, next, current) { // ... you could trigger something here ... });
以下事件也可用(它们的回调函数采用不同的参数):
参见美元的路线文档。
还有另外两个无证事件:
看到$locationChangeSuccess和$locationChangeStart之间的区别是什么?
$rootScope.$on( "$routeChangeStart", function(event, next, current) { //..do something //event.stopPropagation(); //if you don't want event to bubble up });
如果你不想把手表放在特定的控制器中,你可以在Angular应用run()中为整个应用添加手表
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) { //if you want to interrupt going to another location. event.preventDefault(); });
这是为初学者准备的。像我这样的人,
<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>
角:
//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:.... }); });
希望这能帮助像我这样的初学者。以下是完整的工作示例:
<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>
由于某种原因,建议的解决方案不适合我使用routeChangeStart美元事件
如果你遇到同样的问题,试试:
$scope.$on('$stateChangeStart', function(evt, toState, toParams, fromState, fromParams) { // ... you could trigger something here ... });
在我的配置中,我使用了来自节点包管理器(npm)的@ui-router/angularjs (a.k.a angular-ui-router)