javascript 关于 Angular 的位置变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18325406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:29:29  来源:igfitidea点击:

On location change in Angular

javascriptangularjslocationhref

提问by Deepsy

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?

有没有办法检测 AngularJS 中的全局位置变化,而不仅仅是单个控制器?我的目标是检测每个位置变化。或者有什么有效的方法可以观察 window.location.href 的变化?

$routeChangeSuccess 

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

据我了解仅适用于单个控制器还是我错了?

回答by Samuel Horwitz

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

首先,$routeChangeSuccess不限于单个控制器。它是从 广播的,$rootScope这意味着它可以在每个范围(或从 继承的每个范围$rootScope)上侦听,但它是一个应用程序范围的事件。

There is also an undocumented event that works similar to $routeChangeSuccesscalled $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()).

还有一个未记录的事件,其工作方式类似于$routeChangeSuccess调用$locationChangeSuccess。区别在于前者在路由成功更改后触发,后者在 URL 更改但在路由更改之前触发。请注意,这并不是所有 URL 更改,只是 URL 以 AngularJS 应用程序可以注册它的方式更改的次数(例如,对 的 setter 调用$location.url())。

Just to clarify, $locationChangeSuccessis broadcast from the $rootScopeas well.

只是为了澄清,$locationChangeSuccess是广播从$rootScope也。

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

对于这两种情况,您都可以使用scope.$on('$routeChangeSuccess')或收听事件scope.$on('$locationChangeSuccess')

回答by user3522492

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

对于那些使用 Angular-UI-Router 的人,这个事件不会触发。“$stateChangeSuccess” 是 Angular-UI-Router 的正确事件。有关 UI 路由器事件的更多信息,请参阅此 SO 问题:
如何触发 UI 路由器视图加载事件?
以及 API 指南:https:
//github.com/angular-ui/ui-router/wiki#state-change-events