从控制器内检测ui-router状态变化并相应地关闭Modal

Sat*_*kar 1 angularjs angular-ui-bootstrap angular-ui-router

我使用该$modal.open({...})方法打开UI-Bootstrap模式.当用户按下后退按钮时,我需要关闭它.

在这种情况下result,该open()方法返回的promise 无用,因为它无法检测由于后退按钮导致的状态更改.现在,当按下后退按钮时,状态会发生变化,但模态会保持打开状态.

基本上我有这个问题的确切问题,但即使它有一个选定的答案,问题也没有解决,从评论中可以看出.这个问题类似,但也没有解决后退按钮问题.

我需要一些方法来检测当前状态是否已从控制器和调用$modalInstance.close()$scope.$close()方法中发生变化.

我可以监听$stateChangeStart事件并检查fromState参数以有条件地关闭模态.但是,此事件也将不必要地继续为所有后续状态更改而触发.

更新:所以我试着听一下这个事件,并在第一次被解雇时立即取消注册.这样我就可以听到后退按钮状态的变化,然后在我想要的时候停止它.模态的最终代码如下:

$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("^");
        });
    },
});
Run Code Online (Sandbox Code Playgroud)

我仍然认为应该有更好的方法来做到这一点.Constellates显然决定modal.js完全从ui-bootstrap 转储.我是否应该这样做,并简单地使用普通的Bootstrap CSS渲染模态<ui-view/>

tpi*_*pie 5

我需要解决同样的问题.也许是一个略有不同的设置,但我相信它可能对你有用.

我正在使用angular-modal-service,我相信无论如何都在bootstrap上运行.

在模态控制器内部,我使用了以下内容:

$scope.$on('$stateChangeStart', function() {
    $scope.stateChange();
});

$scope.stateChange = function() {
    //  Manually hide the modal using bootstrap.
    $element.modal('hide');
    //  Now close as normal, but give 500ms for bootstrap to animate
    close('', 500);
};
Run Code Online (Sandbox Code Playgroud)

第二个功能只是根据"我不想在按钮上使用'数据关闭'属性下的文档退出模态的手动方式,如何手动关闭模态?".它说:

您需要做的就是获取控制器中的模态元素,然后调用bootstrap模态函数来手动关闭模态.然后正常调用close函数

所以现在,如果状态发生变化(包括用户发起的后退按钮点击),模态会优雅地消失.