我有一个 AngularJs 应用程序,它正在检测状态的更改(使用 ui.router),以便向用户提供保存未保存更改的选项。现在我用确认对话框来执行此操作:
$scope.$on('$stateChangeStart', () => {
if (self.changed && confirm('There are unsaved changes. Do you want to save them?'))
this.save();
});
我想将其更改为使用$modal
来自 bootstrap ui 库的对话框。我遇到的问题是$modal.open()
调用立即返回(异步),状态在打开对话框之前发生变化,并且从未打开。
$scope.$on('$stateChangeStart', () => {
if (self.changed)
this.$dialog.open({...}).result.then(()=>{
this.save();
});
});
有没有办法克服这个问题,还是我坚持使用普通的 javascript 确认对话框?
这就是我解决问题的方法。在我的应用程序中,我使用 AppCtrl(父级)来处理导航、脏状态等。
function AppCtrl($rootScope, events, modalDialog) {
var vm = this,
handlingUnsavedChanges = false;
function isDirty() {
return $rootScope.$broadcast(events.CAN_DEACTIVATE).defaultPrevented;
}
function onStateChangeStart(event, toState, toParams) {
if (handlingUnsavedChanges) {
// if the dirty state has already been checked then continue with the state change
return;
}
// check for dirty state
if (isDirty()) {
// cancel navigation
event.preventDefault();
modalDialog
.confirmNavigation()
.then(function () {
// ignore changes
handlingUnsavedChanges = true;
$state.go(toState.name, toParams);
});
}
// Else let the state change
}
$rootScope.$on('$stateChangeStart', onStateChangeStart);
}
<div ng-controller="AppCtrl as app">
<div ui-view />
</div>
然后,您可以在路由控制器中添加 CAN_DEACTIVATE 事件的事件处理程序来检查脏状态,例如
function UserDetailCtrl($scope, events) {
function isDirty() {
// Your logic, return a boolean
}
function canDeactivate(e) {
if (isDirty()) {
e.preventDefault();
}
}
$scope.$on(events.CAN_DEACTIVATE, canDeactivate);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)