是否可以进行自定义“离开页面”确认?

时间:2014-06-15 21:52:04

标签: javascript angularjs

我希望能够暂停执行,显示对话框,然后按下某个按钮,然后继续执行。

因此,如果用户在我的表单上,然后单击指向其他路径的链接,我希望我的对话框显示,然后如果他们点击该对话框上的确认按钮,则路径将继续。

所以我知道有一个$ routeChangeStart,它有下一个路由作为第一个参数,但它只包含偶数和一些范围的名称。您可以使用preventDefault来停止路由,但我想知道以后是否有办法继续路由?

所以最好在routeChangeStart中我会做event.preventDefault(),然后再存储,然后在用户点击确认后,我会采取" next"并重做路线。

如何重做路线? 我知道我可以使用params对象然后$ location在originalPath上执行str_replace,但我想知道是否有更直接的方法重新应用路由更改?

2 个答案:

答案 0 :(得分:0)

恐怕你无法避免字符串解析。

如果要异步处理确认,则确实需要在默认情况下阻止该事件,要求用户确认,如果已授予,请设置一个标志并使用$location.url(...)导航到请求的页面。

app.controller('myCtrl', function ($location, $scope, UserConfirm) {
    $scope.$on('$locationChangeStart', function (evt, next, prev) {
        if (!$scope.exitConfirmed) {
            evt.preventDefault();
            var url = extractUrl(prev, next);
            UserConfirm.confirm('Are you sure you want to leave ?').then(
                function (confirmed) {
                    if (confirmed) {
                        $scope.exitConfirmed = true;
                        $location.url(url);
                    }
                }
            );
        }
    });
    ...
});

extractUrl()函数可能如下所示:

function extractUrl(prevAbsUrl, nextAbsUrl) {
    var idx = prevAbsUrl.length - $location.url().length;
    var withNumSign = nextAbsUrl.substring(idx);
    var pureUrl = withNumSign.substring(withNumSign.indexOf('/'));
    return pureUrl;
}

另请参阅此 short demo

答案 1 :(得分:0)

如果使用$ locationChangeStart,则next和current只是表示当前和未来目标的完整URL的字符串,因此不需要解析。

所以我的解决方案是:

function confirmLeaving(evt, next, current) {
  if(consideringClosing)  //ok we're allowed to leave now
    return;

  evt.preventDefault();  //Don't leave! Show dialog instead.

  $('#dialogCancel').modal('show');
  consideringClosing = true;  //if we try to leave again while dialog is up, thats fine.
}   

$scope.$on('$locationChangeStart', confirmLeaving);

然后在模态中我有一个按钮“关闭而不保存”,它将$ location返回到项目列表,但是现在我已将considerationClosing设置为true,confirmLeaving将不会停止用户。在模态中还有一个取消按钮,它关闭模态并将considerationClosing设置为false(因此模态将在locationChange上再次显示)。