AngularJS ng-model Directive
The ng-model
directive binds application data to the value of HTML controls (input, select, textarea).
ng-model Directive
The ng-model
directive can bind the value of an input field to a variable created by AngularJS.
AngularJS Example
Two-Way Binding
Two-way binding, changes made to the input field will also affect the AngularJS property:
AngularJS Example
Validating User Input
AngularJS Example
In the above examples, the alert message will be displayed if the ng-show
attribute returns true
.
Application Status
The ng-model
directive can provide status values for application data (invalid, dirty, touched, error):
AngularJS Example
<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">
Email:
<input type="email" name="myAddress" ng-model="myText" required>
<p>Edit the email address to see the status change.</p>
<h1>Status</h1>
<p>Valid: {{myForm.myAddress.$valid}} (true if the input is valid).</p>
<p>Dirty: {{myForm.myAddress.$dirty}} (true if the value has changed).</p>
<p>Touched: {{myForm.myAddress.$touched}} (true if the field has been clicked).</p>
CSS Classes
The ng-model
directive provides CSS classes to HTML elements based on their state:
AngularJS Example
The ng-model
directive adds/removes the following classes based on the state of the form field:
- ng-empty
- ng-not-empty
- ng-touched
- ng-untouched
- ng-valid
- ng-invalid
- ng-dirty
- ng-pending
- ng-pristine