The ng-model directive binds HTML elements to application data.
The ng-model directive can also:
- Provides type validation (number, email, required) for application data.
- Provides state (invalid, dirty, touched, error) for application data.
- Provides a CSS class for HTML elements.
- Binds HTML elements to an HTML form.
Two-way binding
<div ng-app= "myApp" ng-controller= "Myctrl" >
Name: <input ng-model= "Name" >
</div>
Validating user input
<form ng-app= "" Name= "MyForm" >
Email:
<input type= "Email" name= "myAddress" ng-model= "text" >
<span ng-show= "myform.myaddress. $error. Email" > Not a valid email address </span>
</form>
Application Status
The Ng-model directive can provide status values for application data (invalid, dirty, touched, error):
<form ng-app= "" Name= "MyForm" ng-init= "myText = ' [email protected] ' >
Email:
<input type= "Email" name= "myAddress" ng-model= "MyText" required></p>
{{myform.myaddress. $valid}}
{{myform.myaddress. $dirty}}
{{myform.myaddress. $touched}}
</form>
Property |
Describe |
$dirty |
The form is filled with records |
$valid |
The contents of the field are valid |
$invalid |
The contents of the field are illegal |
$pristine |
form does not fill in records |
CSS classes
The Ng-model directives provide CSS classes for HTML elements based on their state:
<style>
Input.ng-invalid {
Background-color:lightblue;
}
</style>
<body>
<form ng-app= "" Name= "MyForm" >
Enter your name:
<input name= "myAddress" ng-model= "text" required>
</form>
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
Ng-model directive