The ng-model directive can enforce type validation for application data, such as ensuring values are of type number, email, or required.
<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 example above, the <span> will be shown only if the expression in the ng-show attribute evaluates to true.
If the property specified in the ng-model attribute does not exist, AngularJS will automatically create it for you. |
The ng-model directive can offer status indicators for application data, such as valid, dirty, touched, and error.
<form ng-app=”” name=”myForm” ng-init=”myText = ‘[email protected]'”> Email: <input type=”email” name=”myAddress” ng-model=”myText” required> <h1>Status</h1> {{myForm.myAddress.$valid}} {{myForm.myAddress.$dirty}} {{myForm.myAddress.$touched}} </form> |
The ng-model directive assigns CSS classes to HTML elements based on their status.
<style>
input.ng-invalid {
background-color: lightblue; } </style>
<body> <form ng-app=”” name=”myForm”> |
The ng-model directive adds or removes the following classes based on the status of the form field: