简体   繁体   中英

Detect closing $modal by backdrop

I'm using AngularJS with angularUI-bootstrap. Is there a way to detect when a modal is being closed by clicking on the backdrop? I am trying to change a boolean based on closing of the modal.

Sure, it is very easy to detect closing by ESC / clicking on backdrop. If such an event takes place the result promise will be rejected. So, you can run whatever logic you want by adding error handler to the result promise returned from the $modal.open({...}) method.

You can see this in action in a plunker forked from the demo page ( http://angular-ui.github.io/bootstrap/ ): http://plnkr.co/edit/QJbjkB7BUT5VFInVPyrF?p=preview where the $log.info('Modal dismissed at: ' + new Date()); code is executed on modal's dismiss.

Old question, but if you want to add confirmation dialogs on various close actions, add this to your modal instance controller:

$scope.$on('modal.closing', function(event, reason, closed) {
    console.log('modal.closing: ' + (closed ? 'close' : 'dismiss') + '(' + reason + ')');
    var message = "You are about to leave the edit view. Uncaught reason. Are you sure?";
    switch (reason){
        // clicked outside
        case "backdrop click":
            message = "Any changes will be lost, are you sure?";
            break;

        // cancel button
        case "cancel":
            message = "Any changes will be lost, are you sure?";
            break;

        // escape key
        case "escape key press":
            message = "Any changes will be lost, are you sure?";
            break;
    }
    if (!confirm(message)) {
        event.preventDefault();
    }
});

I have a close button on the top right of mine, which triggers the "cancel" action. Clicking on the backdrop (if enabled), triggers the cancel action. You can use that to use different messages for various close events. This is my way of doing it, thought it might be helpful for others who stumble across your question.

You can do that like so:

var instance = modal.open({ ... })

instance.result.then(function success(){
 //Do success things
},function fail(reason){
  if( ~reason.indexOf('backdrop') ){ 
    // Do things when modal closes on backdrop click
  }
});

This is another quick way to catch a rejected promise (ie modal being dismissed either intentionally or by clicking the background):

$modal.open({ ... })
.result.catch(function(){
   // do something
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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