How to perform an action whenever $uibModal is closed?

Asked

Viewed 430 times

3

How do I perform an action whenever the $uibModal is closed?

Just to facilitate my learning, when I close the modal, I want to display a message.

For example:

angular.module('app', ['ui.bootstrap']).controller('TesteController', function ($scope, $uibModal) {

     $scope.modal = function () {

          var modal = $uibModal.open({
             template: '<div class="modal-body">Olá mundo</div>'
          });

          // Como posso executar isso?

          modal.quandoFechar(function () {
            $scope.mensagem = 'Você fechou o modal';
          });
     };
})

The function modal.quandoFechar obviously does not exist, but I want to know if there is any function that runs a callback when the $uibModalInstance is closed.

1 answer

1


To perform some action with the modal "result", you need to use promisse result and the function then.

All functions then can receive up to three callbacks

  • successCallback is executed when the promise is resolved;
  • errorCallback is executed when the pledge is rejected;
  • notifyCallback is executed when notified.

Whenever a click occurs outside the modal area (in the background) will result in a rejected promisse.

Example:

modal.result.then(function () {
    $scope.mensagem = 'Você fechou o modal';
}, function () {
   $scope.mensagem = 'Clique fora da modal';
});

If you want to show the same message for both cases, or even, perform some action after the execution of the callback passed to the then, it is possible to use the function finally

modal.result.then(function () {
    $scope.mensagem = 'Promisse resolvida';
}, function () {
   $scope.mensagem = 'Promisse rejeitada';
})
.finally(function(){
    $scope.mensagem2 = 'Modal fechada';
});
  • In my case, I preferred to use the finally, because I was "wiping the data" when closing the modal. So regardless if it is "Dismiss" or "close", it performs what is in finally.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.