title: Angular js directive to show alert for browser back button when unsaved data in form
body: <p>I'm a newbie to angularjs.Is there any way to show alert when a form has unsaved data and user presses browser back button.
  Any pointers to how to achieve this would be appreciated.</p>
  
  <p><strong>Update: :</strong> </p>
  
  <pre><code>    angular.module('myApp.directives', []).directive('confirmOnExit', function() {
      return {
          link: function($scope, elem, attrs) {
  
  
              $scope.$on('$locationChangeStart', function(event, next, current) {
  
                  if ($scope.myForm.$dirty) {
                      if(!confirm("Ahh the form is dirty, do u want to continue?")) {
                          event.preventDefault();
                      }
                  }
              });
  
              window.onbeforeunload = function(){
                  alert('me');
                  if ($scope.myForm.$dirty) {
                      return "The Form is Dirty.";
                  }
              }
          }
      };
  });
  </code></pre>
  
  <p><strong>Updated code</strong></p>
  
  <pre><code>    angular.module('myApp.directives', []).directive('confirmOnExit', function () {
      return {
          link: function ($scope, elem, attrs, $rootScope) {
              window.onbeforeunload = function () {
                  if ($scope.myForm.$dirty) {
                      return " do you want to stay on the page?";
                  }
              }
  
              $rootScope.$watch(function {
                  return $location.path();
              },
  
              function (newValue, oldValue) {
                  if (newValue != oldvalue) {
                      // here you can do your tasks
                  } else {}
              },
              true);
  
              $scope.$on('$locationChangeStart', function (event, next, current) {
                  if ($scope.myForm.$dirty) {
                      if (!confirm("The form is dirty, do you want to stay on the page?")) {
                          event.preventDefault();
                      }
                  }
              });
          }
      };
  });
  </code></pre>