OdeToCode IC Logo

Model Options and Pristine Forms In AngularJS

Tuesday, June 10, 2014

Here is a plunk that demonstrates how to reset an Angular form. The form itself will display any element with a dirty flag using a thick red border. The ngModel and ngForm directives automatically add the ng-dirty class to elements with a dirty flag, and the CSS rule applied is like so:

.ng-dirty {
    border: red 5px solid;
}

Notice how typing into an input not only makes the input dirty, but also makes the form itself dirty (a double border).

Dirty AngularJS Form

You might also notice when typing into the first input how the dirty flag takes a couple seconds to appear. The delay is because of the new ngModelOptions directive in 1.3. With ngModelOptions you can specify the events required to push values into the model (perhaps using the blur event instead of the keypress event), and also debounce the data binding by specifying a number of quiet milliseconds to elapse before pushing data. The example plunk is waiting for 2,000 milliseconds.

<form name="editUserForm">

    <input type="text" ng-model="user.firstName" ng-model-options="{debounce:1000}"/>
    <input type="text" ng-model="user.lastName"/>
    <input type="submit" value="Submit"/>
    <input type="button" value="Reset" ng-click="reset()"/>

</form>

The reset button will set the form back into a pristine state using $setPristine. $setPristine recursively sets all the controls inside the form to a pristine state, too. It’s up to the application logic to replace the data, perhaps by making a copy of the original form data, as shown below.

$scope.user = {
    firstName: "Scott",
    lastName: "Allen"
};

$scope.originalUser = angular.copy($scope.user);

$scope.reset = function(){
    $scope.user = angular.copy($scope.originalUser);
    $scope.editUserForm.$setPristine();
};

Quite a bit of power from a minimum amount of code.