AngularJS UI router $ onLocationChangeStart event.PreventDefault not working

I need a way to interrupt a user navigating to a new page when there are unsaved changes on the current page. I have implemented a modified version of the solution here:

http://weblogs.asp.net/dwahlin/cancelling-route-navigation-in-angularjs-controllers

However, what I see in the browser is that as soon as the user clicks on the link, the view changes and the new controller loads completely while the modal dialog is displayed. When the user clicks "cancel" and "event.preventDefault", the user simply ends up with a new view. This is weird because everything I've read indicates that this is the accepted method and no one seems to have this problem. However, I cannot see for me what is wrong with my code.

Here's a function in the main app to handle location changes (ModalService just wraps the angular bootstrap $ modal service):

    onRouteChangeOff = $rootScope.$on('$locationChangeStart', routeChange);

    function routeChange(event, newUrl, oldUrl) {
        //Navigate to newUrl if the form isn't dirty
        if (!$rootScope.unsavedChanges) return;

        var modalOptions = {
            closeButtonText: 'Cancel',
            actionButtonText: 'Ignore Changes',
            headerText: 'Unsaved Changes',
            bodyText: 'You have unsaved changes. Leave the page?'
        };

        ModalService.showModal({}, modalOptions).result.then(function () {
                $rootScope.unsavedChanges = false;
                $location.path(newUrl); //Go to page they're interested in
            }
        , function () {
            event.preventDefault();
        });         
        return;
    }

      

Any ideas?

+3


source to share


1 answer


If anyone else has this problem, the fix turned out to be pretty simple. I moved the code to the stateChangeStart event. The code looks like this:



    onRouteChangeOff = $rootScope.$on('$stateChangeStart', routeChange);

    function routeChange(event, newState) {
        //Navigate to newUrl if the form isn't dirty
        if (!$rootScope.unsavedChanges) return;
        event.preventDefault();
        var modalOptions = {
            closeButtonText: 'Cancel',
            actionButtonText: 'Ignore Changes',
            headerText: 'Unsaved Changes',
            bodyText: 'You have unsaved changes. Leave the page?'
        };

        ModalService.showModal({}, modalOptions).result.then(function () {
            $rootScope.unsavedChanges = false;
            $state.go(newState); //Go to page they're interested in
        });
    }

      

+4


source







All Articles