我在控制器中有一个表单.
如果有未保存的更改,我想警告用户在离开时丢失它们.
如果有未保存的更改,我想警告用户在离开时丢失它们.
首先我试过:
$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(); } }); } });
解决方法
通过监听$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>
希望这个有效!