Warn user before navigating to a different view

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..


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)
  }
}