[英]angularjs- How to call the other controller in app.controller
[英]AngularJS- Prompting the user before routing to other controller to save changes
我在控制器中有一個表單。 如果有未保存的更改,我想警告用戶在離開時丟失它們。
首先我試過:
$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();
拋出一個錯誤$scope.$apply();
:
Error: $digest already in progress
刪除此行只是不執行重定向。
什么是正確的方法呢?
===
編輯:
我嘗試的其他選項是只在我需要取消重定向時才進行處理:
$scope.$on('$locationChangeStart', function (event, next, 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>
希望這個有效!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.