AngularJS input directive

Definition and Usage

AngularJS modifies <input> elements' default behavior, but only if the ng-model attribute exists.

They provide data binding, which means they are part of the AngularJS model and can be referenced and updated in AngularJS functions and DOM.

They provide validation. Example: with required attribute <input> element, as long as it is empty, its $valid The state will be set to false.

They also provide state control. AngularJS saves the current state of all input elements.

The input field has the following states:

  • $untouched This field has not been touched
  • $touched This field has been touched
  • $pristine This field has not been modified
  • $dirty This field has been modified
  • $invalid Field content is invalid
  • $valid Field content is valid

Each state value represents a boolean value, which is true or false.

Example

Input box with data binding:

<input ng-model="myInput">
<p>The value of the input box is:</p>
<h1>{{myInput}}</h1>

Try It Yourself

Syntax

<input ng-model="name">

is used to bind the input field to a model. ng-model attribute.

are used to reference the input element by the value of the

CSS classes within an AngularJS application <input> These classes can be used to set the style of the input element based on its state.

The following classes have been added:

  • ng-untouched This field has not been touched
  • ng-touched This field has been touched
  • ng-pristine This field has not been modified
  • ng-dirty This field has been modified
  • ng-valid Field content is valid
  • ng-invalid Field content is invalid
  • ng-valid-key Validate each key every time. For example:ng-valid-requiredIt is very useful when there is more than one thing to validate.
  • ng-invalid-key For example:ng-invalid-required

If the value represented by the class is falseIf these classes are removed.

Example

Apply styles to valid and invalid input elements using standard CSS:

<style>
input.ng-invalid {
    background-color: pink;
}
input.ng-valid {
    background-color: lightgreen;
}
</style>

Try It Yourself