我有这个代码来确认使用angular-ui路由器以角度导航:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
//checks if campaign has been modified without save.
//if yes state change needs to be confirmed by modal
//otherwise simple navigates away
event.preventDefault();
// var _this = this;
_this.toState = toState;
_this.toParams = toParams;
var modalInstance = bootstrapModals.confirm({
title: "Exit without saving?",
message: "You have changes to the campaign. Leave without saving?"
});
modalInstance.then(function(result) {
$state.go(_this.toState.name, _this.toParams);
}, function(error) {
event.preventDefault();
});
});
然而,$ state.go只会再次显示模态,而不会更改任何路径。 _this.toState.name和_this.toParams中的值是正确的。
问题是什么?
答案 0 :(得分:2)
You have an infinite loop on success. Every time you do a state change, you go back in the code causing the modal to be displayed again. You need to save the answer to prevent the modal from popping back up.
答案 1 :(得分:1)
它还在听routeChange。所以我必须这样做:
onRouteChangeOff = $rootScope.$on('$stateChangeStart', routeChange);
function routeChange (event, toState, toParams, fromState, fromParams) {
//checks if campaign has been modified without save.
//if yes state change needs to be confirmed by modal
//otherwise simple navigates away
// var _this = this;
_this.toState = toState;
_this.toParams = toParams;
var modalInstance = bootstrapModals.confirm({
title: "Exit without saving?",
message: "You have changes to the campaign. Leave without saving?"
});
modalInstance.then(function(result) {
//should stop listening to $stateChangeStart
onRouteChangeOff ();
$state.go(_this.toState.name, _this.toParams);
}, function(error) {
// event.preventDefault();
});
event.preventDefault();
};
答案 2 :(得分:0)
我花了一段时间回家发帖,抱歉。
我不确定ModalInstance是否会以相同的方式运行,但这是使用good' ol确认的代码:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
//checks if campaign has been modified without save.
//if yes state change needs to be confirmed by modal
//otherwise simple navigates awa
// var _this = this;
_this.toState = toState;
_this.toParams = toParams;
var result = confirm('are you sure you want to leave unsaved?');
if(!result) {
event.preventDefault();
}
});
不要先阻止它,如果成功则不要使用$state.go()
,只能防止错误。
你应该可以使用bootstrap模式尝试这样的事情。
答案 3 :(得分:0)
检查
bootstrapModals.confirm({
title: "Exit without saving?",
message: "You have changes to the campaign. Leave without saving?",
callback: function(result) {
if(result) {
//yes
}else {
//no
}
}
});