JavaScript   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – 需要在状态退出时关闭模态大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用UI-Router和angular bootstrap-ui.我有一个状态设置来创建模态’onEnter’.当我试图关闭模态’onExit’时,我现在遇到了问题.这是基本状态.当输入’items.detail’时它将打开一个模态,当该模态被关闭或解除时它将转换为’items’.
.state('items.detail',{
    url: '/{iD}',onEnter: function ($stateParams,$state,$modal,$resourcE) {
        var modalInstance = $modal.open({
            templateUrl: 'views/modal/item-detail.html',controller: 'itemDetailCtrl'
        })
        .result.then(function () {
            $state.transitionTo('items');
        },function () {
            $state.transitionTo('items');
        });
    }
})

我试过像这样使用onExit处理程序.但是无法从该处理程序访问modalInstance或modal所在的范围.我尝试注射的所有东西都是未定义的.

.state('items.detail',function () {
            $state.transitionTo('items');
        });
    },onExit: function ($scope) {
        controller: function ($scope,$modalInstance,$modal) {
            $modalInstance.dismiss();
        };
    }
})

从我的模态控制器中我试着听取状态变化.

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

我已经用$scope和$on和$rootScope.$on尝试了这个,但是每次我在任何状态之间转换时它们都会被调用.这只会在我打开模态后发生.

如果最后一点不清楚…当我刷新我的角度应用程序时,我可以在所有其他状态之间进行转换而不会调用此侦听器事件但是在我打开该模态之后,所有状态更改都会被该侦听器调用,即使之后模态已关闭.

解决方法

我认为你可以更好地组织你的模态开放行为.我不会在状态定义中使用onEnter和onExit处理程序.相反,最好定义应该处理模态的控制器:
.state('items.detail',controller:'ItemDetailsController',template: '<div ui-view></div>'
})

然后定义你的控制器:

.controller('ItemDetailsController',[
    function($stateParams,$resourcE){
        var modalInstance = $modal.open({
            templateUrl: 'views/modal/item-detail.html',controller: 'ModalInstanceCtrl',size: size,resolve: {
                itemId: function () {
                   return $stateParams.id;
            }
         modalInstance.result.then(function () {
                $state.go('items');
            },function () {
                $state.go('items');
         });
      }
    });       
    }
])

然后定义你的ModalInstanceCtrl:

.controller('ModalInstanceCtrl',[ 
    function ($scope,itemId) {

        //Find your item from somewhere using itemId and some services
        //and do your stuff


        $scope.ok = function () {
            $modalInstance.close('ok');
        };

        $scope.cancel = function () {
           $modalInstance.dismiss('cancel');
        };
    };
]);

通过这种方式,modal将在ModalInstanceCtrl中关闭,您不必担心状态的onExit处理程序.

关于在$scope上添加的监听器.似乎在添加侦听器时并且在状态发生变化时永远不会删除它,这会导致内存泄漏,并且每次应用程序更改状态时都会执行处理程序函数!所以最好摆脱那个事件监听器,因为你实际上并不需要它.

大佬总结

以上是大佬教程为你收集整理的javascript – 需要在状态退出时关闭模态全部内容,希望文章能够帮你解决javascript – 需要在状态退出时关闭模态所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。