简体   繁体   English

如何检查Bootstrap UI模式是否打开? -AngularJS

[英]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. 我只能在打开模态的同一开关/案例中使用m.close()。 If I want to close it in another if statement later in the code m is undefined. 如果我想在后面的代码if中的另一个if语句中关闭它,则未定义。

Anyway. 无论如何。 Can I check if a modal is open? 我可以检查模态是否打开吗? If I console.log(m) then there's this: 如果我console.log(m)则是这样的:

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. 但是我无法在应用程序的其他位置访问变量m,因此无法进行检查。

Just add an flag or getter to your ModalService . 只需向您的ModalService添加标志或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. 然后,您可以调用: ModalService.isOpen()来检查模态是否已打开。

Very easy: 很容易:

Since $uibModal always uses a div with class name modal you can just check if any element with that class name exist: 由于$uibModal始终使用类名为modal的div,因此您可以检查是否存在任何具有该类名的元素:

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

由于$ uibModal服务不提供它,因此最简洁的方法是检查主体上的“模态开放”类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM