0

Right now my controller code looks like this:

$scope.spAPI.load(id).then(function(result){
  var deferred = $q.defer();
  if(result !== undefined){
    deferred.resolve($rootScope.$broadcast("onSpLoaded", result));
  }
  return deferred.promise;
}).then(function(success){

      $scope.modalInstance = $modal.open({ ... });


});

I want the modal instance to be opened AFTER the broadcasts are processed. Is there a way to do this?

Update: I was thinking about this problem backwards. I meant to do the broadcast after the modal instance, anyway, nevermind.

PS: I did have problems with the modalinstance.opened callback though, I had to hack my way around it. I am still struggling to use $q correctly, my code has been getting messier.

Alex C
  • 1,334
  • 2
  • 18
  • 41
  • Your code looks fine, it should do what you want. because `$broadcast()` is a synchronous operation, all the event handlers should be called when `$broadcast()` returns – Ye Liu Feb 10 '14 at 20:56

1 Answers1

1

Your controller code looks fine, it should work as expected, you just don't need the deferred object in your first then():

$scope.spAPI.load(id).then(function(result){

  if(result !== undefined){
    $rootScope.$broadcast("onSpLoaded", result);
  }

}).then(function(success){

  $scope.modalInstance = $modal.open({ ... });


});

The reason here is because $broadcast() is synchronous operation, all the event handlers will have been called when $broadcast() returns; and the function in 2nd then() will only be called after the function in the first then() returns, so $modal.open() will be called after all event handlers.

DEMO

Update:

You know that $scope.modalInstance.opened is a promise which will be resolved when the modal gets shown, so you can try the following to achieve what you want:

$scope.spAPI.load(id).then(function(result){
    $scope.modalInstance = $modal.open({ ... });

    $scope.modalInstance.opened.then(function() {
        $rootScope.$broadcast("onSpLoaded", result));
    });
});
Ye Liu
  • 8,946
  • 1
  • 38
  • 34
  • I updated my question. I was just not thinking about my problem the right way. Still learning that $q thing. :) – Alex C Feb 11 '14 at 21:44
  • http://plnkr.co/edit/Nbe4af6pWIGtys1Jt8Fz?p=preview - tried but seems not to work with promises – jantimon Jun 02 '15 at 13:40