Reputation: 992
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.
Upvotes: 4
Views: 4744
Reputation: 1152
This is another quick way to catch a rejected promise (i.e. modal being dismissed either intentionally or by clicking the background):
$modal.open({ ... })
.result.catch(function(){
// do something
});
Upvotes: 0
Reputation: 1991
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.
Upvotes: 2
Reputation: 774
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
}
});
Upvotes: 1
Reputation: 117370
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.
Upvotes: 3