Rebam1 Rebam1 - 1 year ago 103
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="">
<meta charset="utf-8" />
<script src=""></script>

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

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

app.controller('verifyViewChange', function ($location, $scope) {
$scope.$on('$locationChangeStart', function (event) {
alert("I'm preventing you from leaving the page");

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 Source

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(){

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download