Updated June 29, 2023
Definition of AngularJS ng-model
The AngularJS ng-model is an in-built directive that serves as the heart of an AngularJS application. It is used in the HTML view to establish a binding between the view and the model, enabling two-way data binding. This directive is essential for input, select, and textarea HTML elements. It also supports form validations, including text, number, email, and required validations. CSS classes like ng-pristine, ng-dirty, ng-touched, etc.
Syntax
There are various HTML elements with which the ng-model directive is used.
1. Using ng-model with Input Types
- Checkbox
<input type="checkbox" ng-model="modelValue"></input>
<input type="email" ng-model="modelValue"></input>
- Radio
<input type="radio" ng-model="modelValue"></input>
- date
<input type="date" ng-model="modelValue"></input>
- number
<input type="number" ng-model="modelValue"></input>
- text
<input type="text" ng-model="modelValue"></input>
- telephone
<input type="tel" ng-model="modelValue"></input>
- url
<input type="url" ng-model="modelValue"></input>
2. Using ng-model with Select Type
<select ng-model="modelValue" ng-options="reason as reason.desc for reason in reasonsList"></select>
3. Using ng-model with textarea
<textarea ng-model=" modelValue"></textarea>
4. Using ng-model with animations
<input type="number" ng-model=" modelValue" class="my-class"></textarea>
.my-class.ng-invalid {
//CSS changes for invalid model value
}
How ng-model directive works in AngularJS?
In the AngularJS framework, it is very important to know that all the In-Built directives that the AngularJS framework has provisioned will always be denoted with the ng prefix.
The ng-model directive is the heart of the AngularJS application, providing two-way data binding and helping bind the view into the model. By using the ng-model directive in AngularJS, the model value in the view will automatically update the corresponding value in the controller.
Example
Index.html
<html ng-app="modalapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="script.js"></script>
<style>
form div {
margin: 10px 0px;
font-weight: bold;
}
h1 {
color: #4CAF50;
text-align: center;
}
input[type=text], input[type=email], input[type=tel], select, textarea {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=email].ng-invalid {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid red;
border-radius: 4px;
box-sizing: border-box;
background-color: #FA787F;
}
</style>
</head>
<body>
<div ng-controller='ModalController'>
<h1>Application Form</h1><br><br>
<form>
<div>Company :
<input type="text" ng-model="companyName"/>
</div>
<div>First Name :
<input type="text" ng-model="fName"/>
</div>
<div>Email Address :
<input type="email" ng-model="emailId"/>
</div>
<div>Phone :
<input type="tel" ng-model="phone"/>
</div>
<div>New Applicant :
<input type="checkbox" ng-model="newApplicant"/>
</div>
<div>Location :
<select ng-model="locationValue" ng-options="location as location.name for location in locations"></select>
</div>
<div>Job Role :<br>
<div ng-repeat="role in roleList track by $index">
<input type="radio" name="occurrences" ng-value="role" ng-model="model.selectedRole"/>
<label>{{ role }}</label>
</div>
<div>Additional Requirements : <br>
<textarea ng-model="additionalReq"></textarea>
</div>
</div>
</form>
<h2>Verify the details entered : </h2>
<div ng-if="companyName">Company Name : {{companyName}}</div>
<div ng-if="fName">First Name : {{fName}}</div>
<div ng-if="emailId">Email Address : {{emailId}}</div>
<div ng-if="phone">Phone : {{phone}}</div>
<div ng-if="newApplicant">New Applicant : {{newApplicant}}</div>
<div ng-if="locationValue">Location : {{locationValue.name}}</div>
<div ng-if="model.selectedRole">Job Role : {{model.selectedRole}}</div>
<div ng-if="additionalReq">Additional Requirement : {{additionalReq}}</div>
</div>
</body>
</html>
Script.js
angular.module('modalapp', [])
.controller('ModalController', function ($scope) {
$scope.locations = [{'name': 'Mumbai'}, {'name': 'Delhi'}, {'name': 'Noida'}, {'name': 'Banglore'}, {'name': 'Chennai'}];
$scope.roleList = [];
$scope.roleList.push('Consultant');
$scope.roleList.push('Manager');
$scope.roleList.push('Lead Developer');
$scope.roleList.push('Fresher');
$scope.roleList.push('Technical Lead');
$scope.model = {}; //declare model object
//$scope.model.selectedRole = 'Technical Lead'; //if default value needs to be selected
});
The above example shows different ways of using the ng-model directive in the HTML view in an AngularJS application. Using the ng-model directive in the HTML template, we have taken various HTML elements to showcase. We have considered an example of an Application form with a different field, and field validation will be done as the ng-model directive is used.
<input type="text" ng-model="companyName"/>
This is an example of input-type text that accepts all types of text i.e. alphanumeric with any characters, and the input value is two-way bound to ng-model companyName
<input type="email" ng-model="emailId"/>
This is an example of an input-type email that accepts only an email id pattern, and the input value is two-way bound to ng-model emailId. If email id pattern validation fails, then it won’t be reflected in the model value emailid
<input type="tel" ng-model="phone"/>
This is an example of input type tel(telephone) that accepts only numbers, and the input value is two way bound to the ng-model phone. If phone number pattern validation fails, then it won’t be reflected in the model value phone
<input type="checkbox" ng-model="newApplicant"/>
The ng-model directive two-way binds the input type checkbox to the newApplicant model variable.
<select ng-model="locationValue" ng-options="location as location.name for location in locations"></select>
This is an example of using the ng-model directive with the dropdown in the HTML view. The model value store the entire location object of the selected option.
<input type="radio" name="occurrences" ng-value="role" ng-model="model.selectedRole"/>
Here is an example of an <input> element with type=”radio” in AngularJS that allows selecting a single value from a list of options:
<textarea ng-model="additionalReq"></textarea>
This is an example of using ng-model directive with textarea where text can be entered and the value can be two-way bound to ng-model additionalReq.
input[type=email].ng-invalid
Adding an ng-invalid class in CSS Style helps evaluate the ng-model value based on input type and update the CSS style based on validity. We are applying the background color red in case of an invalid email id. This helps the user to know that the value is invalid.
One of the significant features of an AngularJS application is the use of the ng-model directive in the HTML view, which enables two-way data binding. If you see the above example, we haven’t used any Submit button to send data to JS and get back on the HTML view. Refer to the output below
Output 1: Using ng-model directive with different input types, select, and textarea.
Output 2: Input all fields with valid details
Output 3: All value reflected in HTML view
Output 4: Input invalid email id
Output 5: All value except email id reflected in HTML view.
Conclusion
ng-model is a directive in AngularJS that comes with a lot of importance and takes priority level 1 in angularJS application. In addition to this, it also provides the ability to perform different form validation and use CSS classes to handle different behavior of input types. Knowing where and when the ng-model will get triggered is very important.
Recommended Articles
We hope that this EDUCBA information on “AngularJS ng-model” was beneficial to you. You can view EDUCBA’s recommended articles for more information.