Latest web development tutorials
 

AngularJS form Directive


Example

This form's "valid state" will not be consider "true", as long as the required input field is empty:

<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>

<p>The forms's valid state is:</p>
<h1>{{myForm.$valid}}</h1>
Try it Yourself »

Definition and Usage

AngularJS modifies the default behavior of the <form> element.

Forms inside an AngularJS application are given certain properties. These properties describes the current state of the form.

Forms have the following states:

  • $pristine No fields have been modified yet
  • $dirty One or more have been modified
  • $invalid The form content is not valid
  • $valid The form content is valid
  • $submitted The form is submitted

The value of each state represents a Boolean value, and is either true or false.

Forms in AngularJS prevents the default action, which is submitting the form to the server, if the action attribute is not specified.


Syntax

<form name="formname"></form>

Forms are being referred to by using the value of the name attribute.


CSS Classes

Forms inside an AngularJS application are given certain classes. These classes can be used to style forms according to their state.

The following classes are added:

  • ng-pristine No fields has not been modified yet
  • ng-dirty One or more fields has been modified
  • ng-valid The form content is valid
  • ng-invalid The form content is not valid
  • ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be validated
  • ng-invalid-key Example: ng-invalid-required

The classes are removed if the value they represent is false.

Example

Apply styles for unmodified (pristine) forms, and for modified forms:

<style>
form.ng-pristine {
    background-color: lightblue;
}
form.ng-dirty {
    background-color: pink;
}
</style>
Try it Yourself »