title: Showing alert in angularjs when user leaves a page
body: <p>I'm an angularjs new bee. I'm trying to write a validation which alerts the user when he tries to close the browser window.</p>
  
  <p>I have 2 links on my page v1 and v2.When clicked on the links it takes to the specific pages.
  Here is the code to redirect to v1 and v2</p>
  
  <pre><code>angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'])
  
  .config(['$routeProvider', function($routeProvider) {
          $routeProvider.when('/v1', {templateUrl: 'pages/v_1.html', controller: MyCtrl1});
          $routeProvider.when('/v2', {templateUrl: 'pages/v_2.html', controller: MyCtrl2});
          $routeProvider.otherwise({redirectTo: '/v1'});
  }]);
  </code></pre>
  
  <p>I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2.
  Any pointers on how to achieve this would be appreciated.</p>
  
  <p>I got an answer <a href="https://stackoverflow.com/questions/13885718/in-angularjs-how-to-detect-when-user-leaves-template-page">here</a> but it pops up the message after every time interval.</p>
  
  <p><strong><em>Updated Code;</em></strong></p>
  
  <p>Controllers</p>
  
  <pre><code>function MyCtrl1() {
      $scope.$on('$locationChangeStart', function (event, next, current) {
          if ('your condition') {
              event.preventDefault();
  
              MessageService.showConfirmation(
                  'Are you sure?',
              MessageService.MessageOptions.YES_NO, {
                  'YES': function () {
                      blockNavigation = false;
                      $location.url($location.url(next).hash());
                      $rootScope.$apply();
                  },
                  'NO': function () {
                      MessageService.clear();
                      $log.log('NO Selected')
                  }
              });
          }
      });
  }
  MyCtrl1.$inject = [];
  
  
  function MyCtrl2() {}
  MyCtrl2.$inject = [];
  </code></pre>