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 ?
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With