A Form is a collection of controls for the purpose of grouping related controls together.
Form and controls provide validation services, so that the user can be notified of invalid input before submitting a form. This provides a better user experience than server-side validation alone because the user gets instant feedback on how to correct the error. Keep in mind that while client-side validation plays an important role in providing good user experience, it can easily be circumvented and thus cannot be trusted. Server-side validation is still necessary for a secure application.
Simple form
The key directive in understanding two-way data-binding is ngModel. The ngModel directive provides the two-way data-binding by synchronizing the model to the view, as well as view to the model. In addition it provides an API for other directives to augment its behavior.
<div ng-controller=”ExampleController”>
<form novalidate class=”simple-form”>
<label>Name: <input type=”text” ng-model=”user.name” /></label><br />
<label>E-mail: <input type=”email” ng-model=”user.email” /></label><br />
Best Editor: <label><input type=”radio” ng-model=”user.preference” value=”vi” />vi</label>
<label><input type=”radio” ng-model=”user.preference” value=”emacs” />emacs</label><br />
<input type=”button” ng-click=”reset()” value=”Reset” />
<input type=”submit” ng-click=”update(user)” value=”Save” />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module(‘formExample’, [])
.controller(‘ExampleController’, [‘$scope’, function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
Note that novalidate is used to disable browser’s native form validation. The value of ngModel won’t be set unless it passes validation for the input field. For example: inputs of type email must have a value in the form of user@domain.
Using CSS classes
To allow styling of form as well as controls, ngModel adds these CSS classes:
- ng-valid: the model is valid
- ng-invalid: the model is invalid
- ng-valid-[key]: for each valid key added by $setValidity
- ng-invalid-[key]: for each invalid key added by $setValidity
- ng-pristine: the control hasn’t been interacted with yet
- ng-dirty: the control has been interacted with
- ng-touched: the control has been blurred
- ng-untouched: the control hasn’t been blurred
- ng-pending: any $asyncValidators are unfulfilled
The following example uses the CSS to display validity of each form control. In the example both user.name and user.email are required, but are rendered with red background only after the input is blurred (loses focus). This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity.
<div ng-controller=”ExampleController”>
<form novalidate class=”css-form”>
<label>Name: <input type=”text” ng-model=”user.name” required /></label><br />
<label>E-mail: <input type=”email” ng-model=”user.email” required /></label><br />
Gender: <label><input type=”radio” ng-model=”user.gender” value=”male” />male</label>
<label><input type=”radio” ng-model=”user.gender” value=”female” />female</label><br />
<input type=”button” ng-click=”reset()” value=”Reset” />
<input type=”submit” ng-click=”update(user)” value=”Save” />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<style type=”text/css”>
.css-form input.ng-invalid.ng-touched {
background-color: #FA787E;
}
.css-form input.ng-valid.ng-touched {
background-color: #78FA89;
}
</style>
<script>
angular.module(‘formExample’, [])
.controller(‘ExampleController’, [‘$scope’, function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
Binding to form and control state
A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
Similarly, an input control that has the ngModel directive holds an instance of NgModelController. Such a control instance can be published as a property of the form instance using the name attribute on the input control. The name attribute specifies the name of the property on the form instance.
This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives. This allows us to extend the above example with these features:
- Custom error message displayed after the user interacted with a control (i.e. when $touched is set)
- Custom error message displayed upon submitting the form ($submitted is set), even if the user didn’t interact with a control
Custom model update triggers
By default, any change to the content will trigger a model update and form validation. You can override this behavior using the ngModelOptions directive to bind only to specified list of events. I.e. ng-model-options=”{ updateOn: ‘blur’ }” will update and validate only after the control loses focus. You can set several events using a space delimited list. I.e. ng-model-options=”{ updateOn: ‘mousedown blur’ }”
animation showing debounced input
If you want to keep the default behavior and just add new events that may trigger the model update and validation, add “default” as one of the specified events.
I.e. ng-model-options=”{ updateOn: ‘default blur’ }”
Non-immediate (debounced) model updates
You can delay the model update/validation by using the debounce key with the ngModelOptions directive. This delay will also apply to parsers, validators and model flags like $dirty or $pristine.
animation showing debounced input
I.e. ng-model-options=”{ debounce: 500 }” will wait for half a second since the last content change before triggering the model update and form validation.
If custom triggers are used, custom debouncing timeouts can be set for each event using an object in debounce. This can be useful to force immediate updates on some specific circumstances (like blur events).
I.e. ng-model-options=”{ updateOn: ‘default blur’, debounce: { default: 500, blur: 0 } }”
If those attributes are added to an element, they will be applied to all the child elements and controls that inherit from it unless they are overridden.