Code


<!DOCTYPE html> <html> <head> <script src="angular.js"></script> <script src="script.js"></script> <style> label { display: inline-block; width: 100px; vertical-align: middle; } input { display: inline-block; vertical-align: middle; } input.ng-invalid { border: solid red 2px; } </style> </head> <body ng-app="mainModule"> <div ng-controller="mainController"> <form name="personForm" novalidate> <label for="firstNameEdit">First name:</label> <input id="firstNameEdit" type="text" name="firstName" ng-model="person.firstName" required /><br /> <label for="lastNameEdit">Last name:</label> <input id="lastNameEdit" type="text" name="lastName" ng-model="person.lastName" required /><br /> <br /> <button type="button" ng-click="resetForm()" ng-disabled="!isPersonChanged()">Reset</button> </form> <br /> <strong>personForm.$pristine =</strong> {{personForm.$pristine}}<br /> <strong>personForm.$valid =</strong> {{personForm.$valid}} </div> </body> </html>
angular.module("mainModule", []) .controller("mainController", function ($scope) { $scope.person = { firstName: "John", lastName: "Doe" }; var oriPerson = angular.copy($scope.person); $scope.resetForm = function () { $scope.person = angular.copy(oriPerson); $scope.personForm.$setPristine(); }; $scope.isPersonChanged = function () { return !angular.equals($scope.person, oriPerson); }; });

Example


Description


In this example we're going to see how we can reset a form. Remember that there are model variables associated to our input elements so what we're going to do is reset the model to automatically have also the input elements back to their original state.

We've defined the person model variable on the scope and as soon as mainController is initialized, also the oriPerson variable inside it is initialized with a copy of the original person model variable (oriPerson will not be visible on the scope, it's a private variable inside the controller used just to remember the original state of the model). We've defined also the isPersonChanged function that tells if the model is changed by checking if the values are different from the original ones. We use this information to decide if the reset button should be enabled or disabled. Whenever the reset button is pressed, the resetForm function is called and so the person variable goes back to its original state and the state of personForm is reset to pristine by calling the $setPristine function on it.