AngularJS ng-model Directive
The ng-model directive is used to bind application data to the values of HTML controls (input, select, textarea).
ng-model Directive
ng-modelDirectives can bind the values of input fields to variables created by AngularJS.
AngularJS Examples
<div ng-app="myApp" ng-controller="myCtrl">
Name:<input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
Name:<input ng-model="name">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>
Try it Yourself »
Two-way Binding
Two-way binding: when the value of the input field is modified, the value of the AngularJS property will also be modified:
AngularJS Examples
<div ng-app="myApp" ng-controller="myCtrl">
Name:<input ng-model="name">
<h1>You entered:{{name}}</h1>
</div>
Name:<input ng-model="name">
<h1>You entered:{{name}}</h1>
</div>
Try it Yourself »
Validate user input
AngularJS Examples
<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>
Email:
<input type="email" name="myAddress" ng-model="text">
<span ng-show="myForm.myAddress.$error.email">Not a valid email address</span>
</form>
Try it Yourself »
In the above example, the prompt message will be displayedng-showProperty returnstrueunder the following conditions.
Applied state
ng-modelThe directive can provide state values for application data (invalid, dirty, touched, error):
AngularJS Examples
<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 state changes.</p>
<h1>State</h1>
<p>Valid: {{myForm.myAddress.$valid}} (true if the input value is valid).</p>
<p>Dirty: {{myForm.myAddress.$dirty}} (true if the value has changed).</p>
<p>Touched: {{myForm.myAddress.$touched}} (true if clicked via touch screen).</p>
Try it Yourself »
CSS Classes
ng-modelDirectives provide CSS classes to HTML elements based on their state:
AngularJS Examples
<style>
input.ng-invalid {
background-color: lightblue;
}
background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
Enter your name:
<input name="myAddress" ng-model="text" required>
</form>
<body>
<form ng-app="" name="myForm">
Enter your name:
<input name="myAddress" ng-model="text" required>
</form>
Try it Yourself »
ng-modelDirectives add/remove the following classes based on the state of the form fields:
- ng-empty
- ng-not-empty
- ng-touched
- ng-untouched
- ng-valid
- ng-invalid
- ng-dirty
- ng-pending
- ng-pristine