22

In my application, it is using $modal.open() function to open a modal popup which is using another page as a template. While clicking the button, it is showing the modal popup fine. If I click the Cancel button then it is calling this function and working fine also.

    $scope.cancel=function(){
    });

But if the user clicks outside the modal popup, we are unable to catch that event by this code

    $scope.dismiss=function(){
    });

How do I catch that event?

I have seen many articles of AngularJS, but couldn't find a solution for this.

Cœur
  • 37,241
  • 25
  • 195
  • 267

4 Answers4

34

$modal.open() returns a object with a promise. You can use the promise and chain it though, and handle it in the catch. When you click on the backdrop outside, it does a dismiss internally and it rejects the promise.

ex:-

var instance = $modal.open(...);

 instance.result.then(function(){
  //Get triggers when modal is closed
 }, function(){
  //gets triggers when modal is dismissed.
 });

If you are using this in the child where $modalInstance is injected you could do that there as well. So basically rather than dealing with event this helps you do it at a higher level with the help of promises.

PSL
  • 123,204
  • 21
  • 253
  • 243
  • how to return value when user clicks on backdrop , I need to update values in the other controller when dimiss,cancel,backdrop click events,please let me know how to do this ? – ratnakar Jun 08 '15 at 10:41
  • @ratnakar you could return a rejected promise with value ex:- return `$q.reject(value)` from the catch block or just return value which can then be chained in then block. – PSL Jun 08 '15 at 13:35
9

You can use

backdrop: 'static'

in your options. Like this:

var modalInstance = $modal.open({
    templateUrl: 'myModalContent.html',
    controller: 'ModalInstanceCtrl',
    backdrop: 'static',
    ...
});

The Bootstrap 3.0 Documentation explains that backdrop: 'static' specifies a backdrop that doesn't dismiss the modal on click.

BigRon
  • 3,182
  • 3
  • 22
  • 47
Tavousi
  • 14,848
  • 18
  • 51
  • 70
2

Catch all clicks on the html document, and close the modal.

Catch clicks inside the modal and stop the propagation.

i.e.

$("html").on("click",closemodal());

$(".modal").on("click",function(event){
   event.stopPropagation();
}
QuinnFTW
  • 554
  • 5
  • 12
2

I had this same problem with the Angular Mobile UI Demo (1.2), however in the demo files the modal is not declared in the main JS.

Instead, just adding two more variables to the in modal1.html did the trick.

<div class="modal-dialog" ui-outer-click="Ui.turnOff('modal1')" ui-outer-click-if="Ui.active('modal1')">

This is explained here: http://mobileangularui.com/docs/#outer-click

Both properties are needed for it to work.

Kalnode
  • 9,386
  • 3
  • 34
  • 62