Todmy
Todmy

Reputation: 1091

how to force an event to wait for resolving a promise in Angular.js?

I have an angular-ui-router event '$stateChangeStart':

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
  self.onUrlChange_(event);
});

and my onUrlChange_ function, like:

function onUrlChange_(event) {
  ModalDialog.show('confirm', { //this is promise
    bodyContent: {
      i18n: 'forms.unsavedConfirmMessage'
    }
  }).then(function() {}, function () {
    event.preventDefault();
  })
}

So, I want prevent event only if promise was rejected. But this code does not work because of event continues to execute and does not wait for the promise.

Upvotes: 2

Views: 1133

Answers (1)

Vinay Lakhanpal
Vinay Lakhanpal

Reputation: 68

Here is a slight variation to your code. This approach basically cancels the event first and then does a prompt. If prompt is successfull state change event is manually triggered again.

A separate Boolean variable keeps track of if you have already prompted user and prevents you from getting stuck into a loop. Let me know if you have any questions.

//Have an outer variable to check if user has already been shown the modal prompt
var isWarned=false;
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
    if (isWarned === false) {
        //Cancel the original event
        event.preventDefault();
        ModalDialog.show('confirm', {
            bodyContent: {
                i18n: 'forms.unsavedConfirmMessage'
            }
        }).then(function() {}, function() {
            //Mark the isWarned flag so user is not warned again.Resume the navigation
            isWarned = true;
            $state.go(toState.name, toParams);
        })
    }
});

Upvotes: 2

Related Questions