Is there a way to intercept BootstapUI's $uibM

2019-06-16 04:13发布

问题:

I'm using the modal compoenent from Bootstrap UI (https://angular-ui.github.io/bootstrap/) in Angular to render a modal, and on closing I want to be able to redirect to another state, or at least have a function be called.

The problem is I can intercept the close event but whenever I user presses Esc the modal is dismissed and I couldn't find any documentation of catching the dismiss event or assigning a function to the promise that is returned.

The code is as follows:

var modalInstance = $uibModal.open({
  templateUrl: 'a-template.html',
  controller: 'AnotherCtrl',
  controllerAs: 'modal',
  backdrop: false,
  size: 'lg'
});

// I am able to catch this whenever the user exits the modal in an
// orthodox fashion. Doesn't happen when he presses Esc button.
modalInstance.closed = function () {
  $state.go(homeState); 
};

Alternatively another solution that would suit my business case would be to simply not allow the user to dismiss the modal. And close it myself whenever an event happens in the modal controller. I neither found functionality for this so far.

回答1:

In the controller associated with the modal ("AnotherCtrl" or "modal" for you), you can use $scope.$on() with the 'modal.closing' event.

Example:

var modalInstance = $uibModal.open({
  templateUrl: 'a-template.html',
  controller: ['$scope', function($scope){
    $scope.$on('modal.closing', function(event, reason, closed){
        if('condition for not closing')
            event.preventDefault(); //You can use this to prevent the modal from closing            
        else
            window.location = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";            
    });
  }],
  controllerAs: 'modal',
  backdrop: false,
  size: 'lg'
});