我使用$modal.open({...})
方法打开UI-Bootstrap模态。当用户按下后退按钮时,我需要关闭它。检测控制器内的ui路由器状态更改并相应地关闭模态
open()
方法返回的result
诺言在这种情况下无用,因为它无法检测到由于后退按钮导致的状态更改。现在当按下后退按钮时,状态会改变,但模态保持打开状态。
基本上我具有的确切问题是this question,但即使它有一个选定的答案,问题也没有解决从评论中证明的问题。 This other question是类似的,但也不能解决后退按钮问题。
我需要某种方式来检测当前状态是否已从控制器内部发生变化,并调用$modalInstance.close()
或$scope.$close()
方法。
我可以听$stateChangeStart
事件并检查fromState
参数以有条件地关闭模态。但是,这个事件会不必要地为所有后来的状态改变继续触发。
UPDATE:因此,我试着聆听这个事件,并在第一次被解雇后立即注销它。这样我就可以听到后退按钮的状态变化,然后在需要时停止它。模态的最终代码如下:
$stateProvider.state('itemList.itemNew', {
url: '/new',
onEnter: function($state, $modal) {
$modal.open({
templateUrl: "/static/partials/item/form.html",
controller: function($http, $scope, $modalInstance) {
$scope.editableItem = {};
$scope.saveItem = function(item) {
$http.post('/api/item', item)
.success(function(data) {
$modalInstance.close(data);
alert("Saved Successfully");
}).error(function(data) {
alert("There was an error.");
});
};
//Register listener specifically for the back button :(
deRegister = $scope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams) {
if (toState.name === 'itemList' &&
fromState.name === 'itemList.itemNew') {
$modalInstance.close();//Close the modal
deRegister();//deRegister listener on first call
}
}
);
}
}).result.then(function() {
//Promise Resolved, Modal Closed.. So reload
$state.go("^", null, {
"reload": true
});
}, function() {
//Promise Rejected, Modal Dismissed.. no reload
$state.go("^");
});
},
});
我仍然认为应该有更好的方法来做到这一点。 Constellates显然决定从ui-bootstrap转储modal.js
。我是否应该这样做,并简单地使用普通Bootstrap CSS中的模式渲染<ui-view/>
?