AngularJS ng-model Directive

Toggle navigation
TUTORIAL HOME
AngularJS ng-model Directive
❮ Previous Next ❯
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-model Directive
With the ng-model directive you can bind the value of an input field to a variable created in AngularJS.

Example

    Name:

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
    $scope.name = “John Doe”;
});

»
Two-Way Binding
The binding goes both ways. If the user changes the value inside the input field, the AngularJS property will also change its value:

Example

    Name:
   

You entered: {{name}}

»
Validate User Input
The ng-model directive can provide type validation for application data (number, e-mail, required):

Example

    Email:
   
    <span ng-show="myForm.myAddress.$error.email”>Not a valid e-mail address

»
In the example above, the span will be displayed only if the expression in the ng-show attribute returns true.

If the property in the ng-model attribute does not exist, AngularJS will create one for you.

Application Status
The ng-model directive can provide status for application data (invalid, dirty, touched, error):

Example
<form ng-app="" name="myForm" ng-init="myText = 'post@myweb.com‘”>
    Email:
   
   

Status

    {{myForm.myAddress.$valid}}
    {{myForm.myAddress.$dirty}}
    {{myForm.myAddress.$touched}}

»
CSS Classes
The ng-model directive provides CSS classes for HTML elements, depending on their status:

Example

input.ng-invalid {
    background-color: lightblue;
}

    Enter your name:
   

»
The ng-model directive adds/removes the following classes, according to the status of the form field:

ng-empty
ng-not-empty
ng-touched
ng-untouched
ng-valid
ng-invalid
ng-dirty
ng-pending
ng-pristine

❮ Previous Next ❯

Leave a comment