Angularjs Bootstrap modal closing call when clicking outside/esc

bryan picture bryan · May 20, 2015 · Viewed 48k times · Source

I am using the Angular-ui/bootstrap modal in my project.

Here is my modal:

$scope.toggleModal = function () {
    $scope.theModal = $modal.open({
        animation: true,
        templateUrl: 'pages/templates/modal.html',
        size: "sm",
        scope: $scope
    });
}

One is able to close the modal by clicking the ESC button or clicking outside the modal area. Is there a way to run a function when this happens? I am not quite sure how to catch the sort of closing.

I know that I can manually dismiss a modal by having a ng-click="closeModal()" like this:

$scope.closeModal = function () {
    $scope.theModal.dismiss('cancel');
};

Answer

PSL picture PSL · May 20, 2015

Yes you can. It causes a dismiss event and the promise is rejected in that case. Also, note that the $modal.open() method returns an object that has a result property that is a promise.

With the promise you can...

//This will run when modal dismisses itself when clicked outside or
//when you explicitly dismiss the modal using .dismiss function.
$scope.theModal.result.catch(function(){
    //Do stuff with respect to dismissal
});

//Runs when modal is closed without being dismissed, i.e when you close it
//via $scope.theModal.close(...);
$scope.theModal.result.then(function(datapassedinwhileclosing){
    //Do stuff with respect to closure
});

as a shortcut you could write:

 $scope.theModal.result.then(doClosureFn, doDismissFn);

See ref

The open method returns a modal instance, an object with the following properties:

  • close(result) - a method that can be used to close a modal, passing a result
  • dismiss(reason) - a method that can be used to dismiss a modal, passing a reason
  • result - a promise that is resolved when a modal is closed and rejected when a modal is dismissed
  • opened - a promise that is resolved when a modal gets opened after downloading content's template and resolving all variables 'rendered' - a promise that is resolved when a modal is rendered.