Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - event.preventDefault() not working for routeChangeStart in angularjs app

Hope any angularjs gurus can help me with this.Here is my angularjs code

$scope.$on('$routeChangeStart', function(event, next, current) {
                if ($scope.myForm.$dirty) {
                    if(!confirm("Unsaved, do u want to continue?")) {
                        event.preventDefault();
                    }
                }
            });

It alerts in browser back button click when data is dirty, but on clicking cancel or ok it still completes the route change.Seems like event.preventDefault() is not working. Can any one point out what may be wrong

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I had lots of trouble finding this one, but instead of the "$routeChangeStart" event, you can listen to the "$locationChangeStart" event, for which you can prevent default:

$scope.$on("$locationChangeStart", function(event, next, current) {
    if (!confirm("You have unsaved changes, continue navigating to " + next + " ?")) {
        event.preventDefault();
    }
});

You could also always prevent default, store "next", and display a clean JS modal and decide asynchronously.

$locationChangeStart is currently undocumented but referenced here : https://github.com/angular/angular.js/issues/2109


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...