Rebam1 Rebam1 - 9 days ago 7
AngularJS Question

AngularJS warning when leaving page

I know there are a few posts similar to this but I simply can't get any of them to work for me as intended. I'm trying to setup an event handler to listen to a location change on a specific scope. The code looks like this:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="verifyViewChange">
<a href="SwitchToThis.html">Test</a>
</div>

<script>
var app = angular.module('myApp', []);

app.controller('verifyViewChange', function ($location, $scope) {
$scope.$on('$locationChangeStart', function (event) {
event.preventDefault();
alert("I'm preventing you from leaving the page");
});
});
</script>
</body>
</html>


When I load the page I get the warning, but not when clicking on the link. What do I need to do to make it work?

Answer

You should use the native 'beforeunload' event by adding it to the window.

Below is an example:

$scope.addUnloadEvent = function(){
if (window.addEventListener) {
       window.addEventListener("beforeunload", handleUnloadEvent);
   } else {
       //For IE browsers
       window.attachEvent("onbeforeunload", handleUnloadEvent);
   }
}

function handleUnloadEvent(event) {
   event.returnValue = "Your warning text";
};

//Call this when you want to remove the event, example, if users fills necessary info
$scope.removeUnloadEvent = function(){
   if (window.removeEventListener) {
       window.removeEventListener("beforeunload", handleUnloadEvent);
   } else {
       window.detachEvent("onbeforeunload", handleUnloadEvent);
   }
}

//You could add the event when validating a form, for example
$scope.validateForm = function(){
    if($scope.yourform.$invalid){
        $scope.addUnloadEvent();
        return;
    }
    else{
        $scope.removeUnloadEvent();
    }

}