Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalence of window.onbeforeunload in AngularJS for routes

Tags:

angularjs

Regular JavaScript has window.onbeforeunload. How do I emulate the same in AngularJS with HTML5 routes?

There is $beforeRouteChange, but it doesn't allow you to cancel the event as far as I can tell.

To clarify: window.onbeforeunload would work for navigating away from the page, but not for intra page navigation, e.g. going from one controller to another just through the HTML5 history API.

like image 480
Martin Probst Avatar asked Aug 02 '12 12:08

Martin Probst


2 Answers

Add this :

$scope.$on('$destroy', function() {
   window.onbeforeunload = undefined;
});
$scope.$on('$locationChangeStart', function(event, next, current) {
   if(!confirm("Are you sure you want to leave this page?")) {
      event.preventDefault();
   }
});
like image 176
EpokK Avatar answered Oct 18 '22 15:10

EpokK


There is a $locationChangeStart event which can be canceled.

Since it hasn't been documented yet, here is the unit test describing how it affects the $route service. https://github.com/angular/angular.js/blob/v1.0.1/test/ng/routeSpec.js#L63

This doesn't provide a confirmation for the user like window.onbeforeunload does. You need to bring your own dialog service and restart the location change process to get the same effect (or you could just use the synchronous $window.confirm).

like image 23
groner Avatar answered Oct 18 '22 16:10

groner