How would one watch/trigger an event on a route change?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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 - if reloadOnSearch 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?
回答2:
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
});
});
回答3:
$rootScope.$on( \"$routeChangeStart\", function(event, next, current) {
//..do something
//event.stopPropagation(); //if you don\'t want event to bubble up
});
回答4:
$rootScope.$on( \"$routeChangeStart\", function(event, next, current) {
//if you want to interrupt going to another location.
event.preventDefault(); });
Ta的文章
更多文章
0条评论
还没有人评论过~