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>
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 touchedng-touched
This field has been touchedng-pristine
This field has not been modifiedng-dirty
This field has been modifiedng-valid
Field content is validng-invalid
Field content is invalidng-valid-key
Validate each key every time. For example:ng-valid-required
It 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 false
If 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>