Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
路由的AngularJS中window.onbeforeunload的等价性_Angularjs - Fatal编程技术网

路由的AngularJS中window.onbeforeunload的等价性

路由的AngularJS中window.onbeforeunload的等价性,angularjs,Angularjs,常规JavaScript具有window.onbeforeunload。我如何用HTML5路由在AngularJS中模拟同样的情况 有$beforeRouteChange,但据我所知,它不允许您取消活动 澄清:window.onbeforeunload可用于导航离开页面,但不用于页面内导航,例如,仅通过HTML5历史API从一个控制器转到另一个控制器。有一个$locationChangeStart事件可以取消 由于它还没有被记录下来,下面是一个单元测试,描述它如何影响$route服务。 这不会

常规JavaScript具有window.onbeforeunload。我如何用HTML5路由在AngularJS中模拟同样的情况

有$beforeRouteChange,但据我所知,它不允许您取消活动


澄清:window.onbeforeunload可用于导航离开页面,但不用于页面内导航,例如,仅通过HTML5历史API从一个控制器转到另一个控制器。

有一个
$locationChangeStart
事件可以取消

由于它还没有被记录下来,下面是一个单元测试,描述它如何影响
$route
服务。

这不会像
窗口那样为用户提供确认。onbeforeunload
会这样做。您需要使用自己的对话框服务并重新启动位置更改过程以获得相同的效果(或者您可以使用同步
$窗口。确认)。

添加以下内容:

$scope.$on('$destroy', function() {
   window.onbeforeunload = undefined;
});
$scope.$on('$locationChangeStart', function(event, next, current) {
   if(!confirm("Are you sure you want to leave this page?")) {
      event.preventDefault();
   }
});

如果您使用的是angular ui路由器,则需要使用
$stateChangeStart
而不是
$locationChangeStart

当使用用户界面路由器版本1.0.0+时,使用
$transitions.onStart
而不是
$stateChangeStart
。请参阅文档

$stateChange*
事件从1.0.0()版起不再推荐使用:

所有状态事件(即
$stateChange*
和好友)现在都不推荐使用 并在默认情况下禁用。使用 过渡钩子API

中止转换()的示例代码:


@Freewind于2013年5月1日办理了入住手续,以使其能够使用back按钮:对于angular ui路由器,
$stateChangeStart
应使用。它不会像在
窗口中那样处理页面刷新。在卸载之前,我必须在
$rootScope
上侦听
$stateChangeStart
,而不是
$scope
,这样我才能使用它。请注意,如果执行此操作,则需要在当前作用域被销毁(
$scope.$on('$destroy,…)
)时手动注销此事件侦听器。完全正确!将
$locationChangeStart
与angular ui router一起使用,在控制器“启动”时调用,而不是在用户离开页面时调用。
$transitions.onStart({}, function(transition) {
  if (transition.to().name === 'unreachable') {
    return false;
  }
}