user2362525
user2362525

Reputation:

How to check if a Bootstrap UI modal is open? - AngularJS

My application can open a modal if there's already one open. If that's the case I want to close that modal and open the new one after that's done.

Service to open modals:

app.service('ModalService', function($uibModal) {
this.open = function(size, template, content, backdrop, controller) {
    var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: content,
        windowTemplateUrl: template,
        controller: controller,
        backdrop: backdrop,
        size: size,
        resolve: {}
    });
    return modalInstance;
};

Then I open one with:

var m = ModalService.open('lg', '', 'ng-templates/modal.html', true, 'ModalController');

And I can close it with:

m.close();

I can only use m.close() within the same switch/case as I open the modal. If I want to close it in another if statement later in the code m is undefined.

Anyway. Can I check if a modal is open? If I console.log(m) then there's this:

d.$$state.status = 1
d.$$state.value = true

But I cannot access the variable m elsewhere in my app so I cannot check for that.

Upvotes: 4

Views: 16507

Answers (3)

Lesh_M
Lesh_M

Reputation: 616

Since the $uibModal service doesn't provide it, the leanest way is to check for "modal-open" class on the body:

document.body.className.indexOf('modal-open') !== -1

Upvotes: 1

CommonSenseCode
CommonSenseCode

Reputation: 25369

Very easy:

Since $uibModal always uses a div with class name modal you can just check if any element with that class name exist:

//If no modal is open
if (document.getElementsByClassName("modal").length === 0) {
  //do something...
} else {
  // do something when a modal is open
}

Upvotes: 2

Code Spirit
Code Spirit

Reputation: 5051

Just add an flag or getter to your ModalService.

app.service('ModalService', function($uibModal) {
var open = false,
    modalInstance;

this.isOpen = function () {
  return open;
};

this.close = function (result) {
  modalInstance.close(result);
};

this.dismiss = function (reason) {
  modalInstance.dismiss(reason);
};

this.open = function(size, template, content, backdrop, controller) {
    var modal = $uibModal.open({
        animation: true,
        templateUrl: content,
        windowTemplateUrl: template,
        controller: controller,
        backdrop: backdrop,
        size: size,
        resolve: {}
    });

    //Set open
    open = true;

    //Set modalInstance
    modalInstance = modal;

    //Modal is closed/resolved/dismissed
    modal.result.finally(function () {
      open = false;
    });

    return modal;
};
}

You can then call: ModalService.isOpen() to check if your modal is opened.

Upvotes: 5

Related Questions