How to hide/show same modal instance with AngularJS?

Guillaume Morin picture Guillaume Morin · Feb 5, 2014 · Viewed 23.5k times · Source

I'm currently using angular-ui-bootstrap $modal to display a dialog which lets the user search for and pick a file. The list of files comes from box.com, so I use the box API to search for files and generate a thumbnail to display beside each file in the search result.

Thumbnail generation is quite slow and the user needs to call this search dialog multiple times in the same page. So it would be helpful for the user if the search dialog would contain the previous search results when re-opened.

The question is how can I re-use (i.e. show/hide) the same modal instance ? Angular-ui seems to destroy/recreate the dialog each time. Same thing with angular-strap.

Edit

Here is a Plunkr:

var app = angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function($scope, $modal, $log) {

  $scope.open = function() {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl,

    });

    modalInstance.result.then(function() {
      $log.info('Modal closed at: ' + new Date());
    }, 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.

var ModalInstanceCtrl = function($scope, $modalInstance) {

  $scope.friends = [{
    name: 'John',
    phone: '555-1276'
  }, {
    name: 'Mary',
    phone: '800-BIG-MARY'
  }, {
    name: 'Mike',
    phone: '555-4321'
  }, {
    name: 'Adam',
    phone: '555-5678'
  }, {
    name: 'Julie',
    phone: '555-8765'
  }, {
    name: 'Juliette',
    phone: '555-5678'
  }];

  $scope.ok = function() {
    $modalInstance.close('close');
  };

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

};

Answer

Rahul Tiwari picture Rahul Tiwari · May 16, 2016

To create/hide a ng-strap modal you can use it like this:

     var modalInstance;
        $scope.open = function() {    
            modalInstance= $modal.open({
                   templateUrl: 'myModalContent.html',
                   controller: ModalInstanceCtrl,        
            });
 //This is how to show the modal.

        modalInstance.$promise.then(modalInstance.show);
        };

    //When u want to hide the modal use this as written below:    
    $scope.close = function() {
        modalInstance.hide();
    };