AngularJS ng-model directive
AngularJS ng-model directive
The ng-model directive is used to bind application data to the values of HTML controllers (input, select, textarea).
ng-model directive
ng-modelThe directive can bind the value of an input field to a variable created by AngularJS.
AngularJS instance
<
div
ng-app=
"myApp"
ng-controller=
"myCtrl"Name:
<
input
ng-model=
"name"
<
/div
<
scriptvar app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
<
/script
Try it »
Two-way data binding
Two-way data binding, when the value of the input field is modified, the value of the AngularJS property is also modified:
AngularJS instance
<
div
ng-app=
"myApp"
ng-controller=
"myCtrl"Name:
<
input
ng-model=
"name"
<
h1You entered:
{{name}}
<
<h1>
<
<div>Try it »
Validate user input
AngularJS instance
<
form
ng-app=
""
name=
"myForm"Email:
<
input
type=
"email"
name=
"myAddress"
ng-model=
"text"
<
span
ng-show=
"myForm.myAddress.$error.email"Is not a valid email address
<
/span
<
/formTry it »
In the above examples, the prompt information will be displayed whenng-showthe attribute returnstrueApplication state
Commands can provide status values (invalid, dirty, touched, error) for application data:
ng-modelAngularJS instance
<
<
form
ng-app
=
"
"
name
=
"
myForm
"
ng-init
=
"myText = 'test@runoob.com'
"
Email:
<
input
type
=
"
email
"
name
=
"
myAddress
"
ng-model
=
"
myText
"
required
<
pEdit email address, view status changes.
</
p
<
h1
Status
</
h1
<
pValid: {{myForm.myAddress.$valid}} (true if the entered value is valid).
</
p
<
pDirty: {{myForm.myAddress.$dirty}} (true if the value has changed).
</
p
<
pTouched: {{myForm.myAddress.$touched}} (true if touched by screen click).
</
p
Try it »
CSS class
ng-modelDirectives provide CSS classes to HTML elements based on their state:
AngularJS instance
<
style
input.ng-invalid
{background-color:
lightblue;
}
<
/style
<
body
<
form
ng-app=
""
name=
"myForm"Enter your name:
<
input
name=
"myAddress"
ng-model=
"text"
required
<
/formTry it »
ng-modelAdd/remove the following classes based on the form field's state:
- ng-empty
- ng-not-empty
- ng-touched
- ng-untouched
- ng-valid
- ng-invalid
- ng-dirty
- ng-pending
- ng-pristine