Search code examples
eventsangularjspromiseangularjs-routing

AngularJS: how to preventDefault() of an event after promise completes?


I have some code like this:

$scope.$on("$locationChangeStart", function(event, newPath, oldPath) {

    // Do some sync checks
    if (!$scope.isPageAllowed($location.path()))
    {
        // Prevent default for some reason
        event.preventDefault();
    }
});

When I trying to resolve promises like this:

$scope.$on("$locationChangeStart", function(event, newPath, oldPath) {

    // Do some async checks
    $scope.fooPromises().then(function (data) {

         // Prevent default for some reason when promises resolved (only if resolved)
         event.preventDefault();
    });
});

I got successfull event (because of async execution) and after a while prevented event when promises are resolved.

Is there a way to link event with my promises, so it would be prevented exactly after promises being resolved and not streight after function end?


Solution

  • Sorry, this won't work :-). Events are purely synchronous.

    You're looking for $route.resolve. Asynchronous resolution/rejection of routes, to give a controller data or just to check something.

    http://www.egghead.io/video/Kr1qZ8Ik9G8