Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect unsaved changes and alert user using angularjs

Below is the code so far

    <!doctype html> <html ng-app> <head>     <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>     <script type="text/javascript">     function Ctrl($scope) {         var initial = {text: 'initial value'};         $scope.myModel = angular.copy(initial);         $scope.revert = function() {             $scope.myModel = angular.copy(initial);             $scope.myForm.$setPristine();         }     }     </script> </head> <body>     <form name="myForm" ng-controller="Ctrl">         myModel.text: <input name="input" ng-model="myModel.text">         <p>myModel.text = {{myModel.text}}</p>         <p>$pristine = {{myForm.$pristine}}</p>         <p>$dirty = {{myForm.$dirty}}</p>         <button ng-click="revert()">Set pristine</button>     </form> </body> </html> 

How to alert on browser close or url redirect in case there is some unsaved data, so that user can decide whether to continue?

like image 375
iJade Avatar asked Feb 13 '13 11:02

iJade


1 Answers

Something like this should do it:

<!doctype html> <html ng-app="myApp"> <head>     <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>     <script type="text/javascript">     function Ctrl($scope) {         var initial = {text: 'initial value'};         $scope.myModel = angular.copy(initial);         $scope.revert = function() {             $scope.myModel = angular.copy(initial);             $scope.myForm.$setPristine();         }     }      angular.module("myApp", []).directive('confirmOnExit', function() {         return {             link: function($scope, elem, attrs) {                 window.onbeforeunload = function(){                     if ($scope.myForm.$dirty) {                         return "The form is dirty, do you want to stay on the page?";                     }                 }                 $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();                         }                     }                 });             }         };     });     </script> </head> <body>     <form name="myForm" ng-controller="Ctrl" confirm-on-exit>         myModel.text: <input name="input" ng-model="myModel.text">         <p>myModel.text = {{myModel.text}}</p>         <p>$pristine = {{myForm.$pristine}}</p>         <p>$dirty = {{myForm.$dirty}}</p>         <button ng-click="revert()">Set pristine</button>     </form> </body> </html> 

Note that the listener for $locationChangeStart isn't triggered in this example since AngularJS doesn't handle any routing in such a simple example, but it should work in an actual Angular application.

like image 51
Anders Ekdahl Avatar answered Sep 19 '22 03:09

Anders Ekdahl