On location change in Angular

假装没事ソ 提交于 2019-12-10 01:52:38

问题


Is there a way to detect global location changes in AngularJS, not just single controller? My goal is to detect every location change. Or is there any effective way to watch window.location.href for changes?

$routeChangeSuccess 

As I understood is for single controller only or I'm wrong?


回答1:


First of all, $routeChangeSuccess is not limited to a single controller. It is broadcast from the $rootScope which means that it can be listened to on every scope (or, every scope that inherits from $rootScope) but is an application wide event.

There is also an undocumented event that works similar to $routeChangeSuccess called $locationChangeSuccess. The difference is that the former fires once a route has successfully changed and the latter fires when the URL is changed but before the route changes. Note that this isn't all URL changes, just times the URL changes in a way that the AngularJS application can register it (for example, a setter call to $location.url()).

Just to clarify, $locationChangeSuccess is broadcast from the $rootScope as well.

For both, you can listen to the event using scope.$on('$routeChangeSuccess') or scope.$on('$locationChangeSuccess').




回答2:


For those using Angular-UI-Router, this event won't fire. "$stateChangeSuccess" is the right event for Angular-UI-Router. For more information on UI-router events, see this SO question:
How to trigger UI-Router View Load events?
and also the API guide:
https://github.com/angular-ui/ui-router/wiki#state-change-events



来源:https://stackoverflow.com/questions/18325406/on-location-change-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!