Search code examples
javascriptangularjsangular-ui-routerpreventdefault

JS how to continue event prevent default


I am trying to pop modal asking the user if he is sure about to leave the page, while there changes that have not been commited yet.

Those changes are NOT done using a <form> element, but just some changes that were made on a specific object.

I have tried to detect when he tries to leave the page with either the $routeChangeStart and the $routeChangeSuccess like this:

$scope.$on('$routeChangeStart', function(event, current) {
  event.preventDefault();
  ConfirmationModal.fire("Do you sure?", response => {
    if (response) {
      // how to CONTINUE the prevent default??
    }
  });
}

The code above actually stop the propgregation and not let the user to leave the page.

However - after confirmed the modal, I cannot find any way to continue the page moving. I mean, I can prevent default but not continue default.

I have tried also to:

$location.path(PATH) but this just did not work.

Also - even when user re-click about leaving the page again - the event preventdefault is still prevented.


Solution

  • You could add a flag and a conditional:

    Something like

    $scope.allowChange = false;
    
    $scope.$on('$routeChangeStart', function(event, current) {
      // don't do anything when allowChange  === true
      if (!$scope.allowChange) {
        event.preventDefault();
        ConfirmationModal.fire("Do you sure?", response => {
          if (response) {
            $scope.allowChange = true
            $location.path(...) // I forget prop to get new path from
          }
        });
      }
    
    })