如何在路线改变时观察/触发事件?
当前回答
如果你不想把手表放在特定的控制器中,你可以在Angular的app run()中为整个应用程序添加手表。
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.$on("$locationChangeStart", function(event, next, current) {
// handle route changes
});
});
其他回答
注意:这是AngularJS遗留版本的正确答案。有关更新版本,请参阅此问题。
$scope.$on('$routeChangeStart', function($event, next, current) {
// ... you could trigger something here ...
});
以下事件也可用(它们的回调函数采用不同的参数):
routeChangeSuccess美元 routeChangeError美元 $routeUpdate -如果reloadOnSearch属性已设置为false
参见$route文档。
还有另外两个未记录的事件:
locationChangeStart美元 locationChangeSuccess美元
查看$locationChangeSuccess和$locationChangeStart之间的区别是什么?
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
//..do something
//event.stopPropagation(); //if you don't want event to bubble up
});
如果你不想把手表放在特定的控制器中,你可以在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) {
//if you want to interrupt going to another location.
event.preventDefault(); });
由于某种原因,建议的解决方案不适合我使用$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)