AngularJS 中 window.onbeforeunload 路由的等效性 [英] Equivalence of window.onbeforeunload in AngularJS for routes
问题描述
常规 JavaScript 有 window.onbeforeunload.如何使用 HTML5 路由在 AngularJS 中模拟相同的内容?
Regular JavaScript has window.onbeforeunload. How do I emulate the same in AngularJS with HTML5 routes?
有 $beforeRouteChange,但据我所知,它不允许您取消活动.
There is $beforeRouteChange, but it doesn't allow you to cancel the event as far as I can tell.
澄清:window.onbeforeunload 可用于导航离开页面,但不适用于页面内导航,例如仅通过 HTML5 历史 API 从一个控制器转到另一个控制器.
To clarify: window.onbeforeunload would work for navigating away from the page, but not for intra page navigation, e.g. going from one controller to another just through the HTML5 history API.
推荐答案
有一个 $locationChangeStart
事件可以取消.
There is a $locationChangeStart
event which can be canceled.
由于它还没有被记录下来,这里是描述它如何影响 $route
服务的单元测试.https://github.com/angular/angular.js/blob/v1.0.1/test/ng/routeSpec.js#L63
Since it hasn't been documented yet, here is the unit test describing how it affects the $route
service.
https://github.com/angular/angular.js/blob/v1.0.1/test/ng/routeSpec.js#L63
这不会像 window.onbeforeunload
那样为用户提供确认.您需要带上自己的对话服务并重新启动位置更改过程才能获得相同的效果(或者您可以只使用同步 $window.confirm
).
This doesn't provide a confirmation for the user like window.onbeforeunload
does. You need to bring your own dialog service and restart the location change process to get the same effect (or you could just use the synchronous $window.confirm
).
这篇关于AngularJS 中 window.onbeforeunload 路由的等效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!