Prevent AngularJS modal from closing based on logic inside the modal controller

纵然是瞬间 提交于 2019-12-24 03:21:23

问题


Is there a way to prevent the an AngularJS modal from closing/dismissing in the controller logic of the modal?

What I want is to show a warning when the users closes the modal and the form inside the modal contains unsaved data.

I've tried searching for a before close event or something else I could use in the official documentation, but no luck so far.


回答1:


You can watch the 'modal.closing' event, broadcasted to the modal's scope, like this:

.controller('modalCtrl', function($scope, $modalInstance) {

  $scope.$on('modal.closing', function(event, reason, closed) {
      var r = prompt("Are you sure you wanna close the modal? (Enter 'YES' to close)");

      if (r !== 'YES') {
        event.preventDefault();
      }
  });
})

The first parameter is the event, which you can preventDefault() to prevent it from closing.

The second parameter is the reason (whatever is passed to the $close() method)

The third parameter is a boolean indicating whether the modal was closed or dismissed.

Here a working plunker

I don't know when this was added, but currently it is mentioned in the official documentation.




回答2:


If you set backdrop: 'static' in your modalInstance, solve the problem?

Like this:

var modalInstance = $modal.open({
  ...
  backdrop: 'static',
  ...
});

Then, you need only control the ngClick button responsible to close the modal.

Hope this helps.

UPDATE 1 [only more info]

Use keyboard: false for disable Escape:

var modalInstance = $modal.open({
  ...
  backdrop: 'static',
  keyboard: false
  ...
});

UPDATE 2

I researched and found an option. In your modal controller, use:

$modalInstance.result.then(function (e) {
    //...
}, function (e) {
    //called before modal close
});

Example:

var modalInstance = $modal.open({
  templateUrl: templateUrl,
  controller: modalController
});

function modalController($scope, $modalInstance){

... //your code

  $modalInstance.result.then(function (e) {
      //...
  }, function (e) {
      //called before modal close
  });

... //your code

}

But you need a way to not continue the events for to close the modal. Or allow user save the data before close modal. That's what got so far.

UPDATE 3

Check this.




回答3:


This will stop the backdrop from triggering a $modal.close event:

$modal.open({
   // ... other options
   backdrop  : 'static',
   keyboard  : false
});

The keyboard's ESC key can still close the modal, so if you want to diable that use keyboard: false



来源:https://stackoverflow.com/questions/28429499/prevent-angularjs-modal-from-closing-based-on-logic-inside-the-modal-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!