加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS-在路由到其他控制器之前提示用户以保存更改

发布时间:2020-12-17 16:58:55 所属栏目:安全 来源:网络整理
导读:我在控制器中有一个表单. 如果有未保存的更改,我想警告用户在离开时丢失它们. 首先我试过: $scope.$on('$locationChangeStart',function (event,next,current) { if ($scope.settingsForm.$dirty) { event.preventDefault(); $scope.theUserWantsToLeave(fu
我在控制器中有一个表单.
如果有未保存的更改,我想警告用户在离开时丢失它们.

首先我试过:

$scope.$on('$locationChangeStart',function (event,next,current) {

    if ($scope.settingsForm.$dirty) {

        event.preventDefault();

        $scope.theUserWantsToLeave(function (result) {

            if (result === "LEAVE") {

                $location.path($location.url(next).hash());
                $scope.$apply();

            }
        });
    }

上面的代码在行$scope中抛出一个错误.$apply();:

Error: $digest already in progress

删除此行只是不执行重定向.

什么是正确的方法呢?

===

编辑:

我尝试的其他选项是只在我需要取消重定向时才进行处理:

$scope.$on('$locationChangeStart',current) {

    if ($scope.settingsForm.$dirty) {

      $scope.theUserWantsToLeave(function (result) {

        if (result === "STAY_HERE") {

          event.preventDefault();

        }
          });
        }
});

当以这种方式做事时,UI正在破碎(我看到对话框然后它就消失了).
似乎我在处理事件时无法调用另一个异步方法.

解决方法

通过监听$locationChangeSuccess然后将$route.current分配给最后一个路由,我设法通过路由更改来中断.

此外,如果$scope.theUserWantsToLeave是异步的,那么传递给它的回调可能会触发太晚而无法停止路由更改.您可以使用阻止标志来解决异步调用,例如我的示例中的okToDiscardChanges.

JS:

$scope.okToDiscardChanges = false;

var lastRoute = $route.current;    
$scope.$on('$locationChangeSuccess',function () {
    if ($scope.settingsForm.$dirty && !$scope.okToDiscardChanges) {
        $route.current = lastRoute;
        $scope.errorMessage = 'You have unsaved changes. Are you sure you want to leave?';
    }
});

HTML:

<form name="settingsForm">
    <!-- form stuff -->
</form>

<div ng-show="errorMessage">
    {{ errorMessage }}
    <label>
        <input type="checkbox" ng-model="okToDiscardChanges"> Discard Changes
    </label>
</div>

希望这个有效!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读