AngularJS ng-model directive
- Previous Page AngularJS Directives
- Next Page AngularJS Data Binding
ng-model
Instructions bind the value of HTML controls (input, select, textarea) to application data.
ng-model instruction
Using ng-model
Instructions allow you to bind the value of an input field to a variable created in AngularJS.
Example
<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 = "Bill Gates"; }); </script>
Bidirectional binding
Binding is bidirectional. If the user changes the value in the input field, the AngularJS attribute will also change its value:
Example
<div ng-app="myApp" ng-controller="myCtrl"> Name: <input ng-model="name"> <h1>You entered: {{name}}</h1> </div>
Validate user input
ng-model
Instructions can provide type validation for application data (numbers, emails, required):
Example
<form ng-app="" name="myForm"> Email: <input type="email" name="myAddress" ng-model="text"> <span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span> </form>
In the above example, only when ng-show
the expression returned in the attribute true
then the span will be displayed.
If ng-model
If the property does not exist in the attribute, AngularJS will create one for you.
Application state
ng-model
Instructions can provide the state of application data (valid, dirty, touched, error):
Example
<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com'"> Email: <input type="email" name="myAddress" ng-model="myText" required> <h1>Status</h1> {{myForm.myAddress.$valid}} {{myForm.myAddress.$dirty}} {{myForm.myAddress.$touched}} </form>
CSS class
ng-model
Instructions provide CSS classes based on the state of HTML elements:
Example
<style> input.ng-invalid { background-color: lightblue; } </style> <body> <form ng-app="" name="myForm"> Enter your name: <input name="myName" ng-model="myText" required> </form>
ng-model
The following classes are added or removed from directives based on the status of form fields:
- ng-empty
- ng-not-empty
- ng-touched
- ng-untouched
- ng-valid
- ng-invalid
- ng-dirty
- ng-pending
- ng-pristine
- Previous Page AngularJS Directives
- Next Page AngularJS Data Binding