KingJames
KingJames

Reputation: 556

AngularJS modal async close doesn't work

I am creating a modal and closing it once data comes in the background.

var modal = modal.open({..some params..});

//after data loads
modal.close();

So my problem is, since everything is asynchronous if my data comes instantaneously then my modal.close() executes before modal opens fully and then my screen remains stuck with the modal screen.

One solution I found is adding a timeout to the modal.close

$timeout(function() {
 modal.close();
}, 1)

This works but is it the right way to do it? Or there is some other better solution?

Upvotes: 1

Views: 562

Answers (1)

Kristján
Kristján

Reputation: 18803

The modal instance has an opened promise on it that you should use to guarantee the modal has finished opening before you try to close it. From the docs:

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.

Mixing it with your HTTP request might look like

modal = $modal.open({...})
$http.get(...).then(function(response) {
  modal.opened.then(modal.close)
})

Here's a demo of both the way you're currently doing it and doing it using opened.

$scope.open = ->
  modalInstance = $modal.open(
    templateUrl: 'myModalContent.html',
    controller: 'ModalInstanceCtrl'
  )

  if $scope.work
    modalInstance.opened.then(->
      modalInstance.close()
    )
  else 
    modalInstance.close()

Upvotes: 2

Related Questions