Search code examples
javascriptangularjsangular-uiangular-ui-bootstrap

Delay angular-ui modal from closing


I am using angularjs with the angular-ui library (specially the angular-ui-bootstrap one).

How can I delay a modal from closing? After the user clicks on the x, or Cancel button, I need the modal to stay visible for an extra half second, but I haven't found a way to do it.

I was thinking to add some timeout in the callback function that is passed into the then function of the modal instance, such as:

modalInstance.result.then(function success(){
    // timeout .5 second
}, function cancel() {
   // timeout .5 second
});

but the code in the callback functions is actually run after the modal has been close. Is there a way to do this?


Solution

  • You can use

     $timeout(function() {
         $modalInstance.dismiss('cancel');
     }, 500);
    

    Plunker

    Complete code with seperate controller of modal :-

    angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
    angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $modal, $log) {
    
      $scope.items = ['item1', 'item2', 'item3'];
    
      $scope.open = function (size) {
    
        var modalInstance = $modal.open({
          templateUrl: 'myModalContent.html',
          controller: 'ModalInstanceCtrl',
          size: size,
          resolve: {
            items: function () {
              return $scope.items;
            }
          }
        });
    
        modalInstance.result.then(function (selectedItem) {
          $scope.selected = selectedItem;
        }, function () {
          $log.info('Modal dismissed at: ' + new Date());
        });
      };
    });
    
    // Please note that $modalInstance represents a modal window (instance) dependency.
    // It is not the same as the $modal service used above.
    
    angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $modalInstance,$timeout, items) {
    
      $scope.items = items;
      $scope.selected = {
        item: $scope.items[0]
      };
    
      $scope.ok = function () {
        $modalInstance.close($scope.selected.item);
      };
    
      $scope.cancel = function () {
        $timeout(function() {
                $modalInstance.dismiss('cancel');
            }, 500);
    
      };
    });