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

前端之家收集整理的这篇文章主要介绍了AngularJS-在路由到其他控制器之前提示用户以保存更改前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在控制器中有一个表单.
如果有未保存的更改,我想警告用户在离开时丢失它们.

首先我试过:

$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>

希望这个有效!

猜你在找的Angularjs相关文章