4

I'm trying to prevent user to leave a form if he changed something in it in Angular. I've read some articles about this and found $locationChangeStart. The problem is that this method doesn't get triggered after I modify something in the form and then navigate to other page. Only the window.onbeforeunload is called.

Here is the directive:

.directive(
            'confirmOnExit',
            function() {
                return {
                    link : function($scope, elem, attrs) {
                        $scope
                                .$on(
                                        '$locationChangeStart',
                                        function(event, next, current) {
                                            if ($scope.addEventForm.$dirty) {
                                                if (!confirm("The form is dirty, do you want to stay on the page?")) {
                                                    event.preventDefault();
                                                }
                                            }
                                        });
                        window.onbeforeunload = function() {
                            if ($scope.addEventForm.$dirty) {
                                return "You have unsaved information!";
                            }
                        };
                    }
                };

Here is the form:

<form name="addEventForm"
            method="POST" ng-controller="formController" confirm-on-exit>
...

</form>

Where i am wrong?

Jones
  • 1,036
  • 5
  • 20
  • 37

1 Answers1

-1

If you come across this, try $rootScope with $locationChangeStart as suggested in the comments. Or if you are using Angular UI-Router, use $stateChangeStart:

$rootScope.$on('$stateChangeStart', warnIfUnsavedChanges);

$routeChangeStart if using ngRoute.

Difference between $locationChangeStart, $routeChangeStart, and $stateChangeStart

Community
  • 1
  • 1
What-About-Bob
  • 649
  • 5
  • 13