Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warn user before navigating to a different view

I would like to warn user and get a confirmation before the user navigates away from certain pages in my application, like composing a new message view. Which events can i capture and cancel/continue to make this happen ?

like image 678
Koder Avatar asked Jul 27 '14 05:07

Koder


2 Answers

You should handle the $locationChangeStart event in order to hook up to view transition event, so use this code to handle the transition validation in your controller/s:

$scope.$on('$locationChangeStart', function( event ) {
  var answer = confirm("Are you sure you want to leave this page?")
  if (!answer) {
    event.preventDefault();
  }
}

also you can use this directive angularjs-unsaved-changes which would be much more reusable than writing it per controller..

like image 59
harishr Avatar answered Sep 28 '22 17:09

harishr


If you have say a link or button navigating to another route or state, you could simply show a modal confirming the navigation:

<a href="" ng-click="goToAnotherState()">Go Away...</a>

$scope.goToAnotherState = function(){

//show modal and get confirmating however your like
  if(modalResponse.Ok){
     $state.go('anotherState');
  }
}

another option would be to do this in the $locationChangeStart event of ui-router, but if you're looking to this only here n there, then the first approach is better. $locationChangeStart approach:

$rootScope.$on('$locationChangeStart', function (event, next, prev) {
  event.preventDefault();
  //show modal
  if(modalResponse.ok){
    var destination = next.substr(next.indexOf('#') + 1, next.length).trim();
    $location.path(destination)
  }
}
like image 28
Mohammad Sepahvand Avatar answered Sep 28 '22 17:09

Mohammad Sepahvand