Don't destroy an Angular Bootstrap modal on cl

2019-07-18 20:21发布

I am using Angular Bootstrap to display a Modal (the one presented here), which works perfectly. However, default behavior of this Angular extension is that the modal is reconstructed (and a new instance of its controller will be creatred) whenever it is closed and then opened again.

Since I have some pretty advanced stuff going on inside the Modal, I would like the modal to just be hidden when it is closed, so that its state remains. I have searched around a bit, but unfortunately could not find a simple and effective answer.

Just hiding it would be an option, but this then has to happen whenever the modal is closed, so also when it closes because the backdrop is clicked. And I want the same animation as when the modal is opened in the normal way.

2条回答
走好不送
2楼-- · 2019-07-18 20:29

As you might already know Angular initializes a controller when the associated view is added to the DOM. So the plugin author might have decided to add and remove the view element so that he does not have to worry about clearing the 'scope'each time user opens and closes the modal.

For example, we have a login box in the modal and if the scope is not cleared, it will keep the filled in details even the next time we show it.

An easy hack to solve your problem will be to wrap the originl modal in a custom directive, reneder it. And just change the display property of your custom modal to show and hide the modal ;)

查看更多
Summer. ? 凉城
3楼-- · 2019-07-18 20:39

Why don't you abstract the modal state into its own service? That way, whenever the modal controller is created, it uses the service to setup the view state on initialisation.

Eg. create a service

.factory('ModalStateService', function(){
    var state = {
        someValue: 'something'
    };

    return {
        getState: function() { return state; }
    };
});

Then in your controller:

.controller('ModalCtrl', function($scope, ModalStateService){
    $scope.viewState = ModalStateService.getState();
});

Then in your modal content view for example:

<span>{{viewState.someValue}}</span>

If you were then to set someValue inside your modal, say through an input, the service state would be updated. Then when you create and destroy your modal, the state will persist.

查看更多
登录 后发表回答