EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials AngularJS Tutorial AngularJS ng-model
Secondary Sidebar
AngularJS Tutorial
  • AngularJS Basic and Advance
    • What is AngularJS
    • Career In AngularJS
    • Uses of Angular JS
    • AngularJS Architecture
    • Angular JS Application
    • AngularJS Application
    • AngularJS Filter Array
    • AngularJS ng-style
    • AngularJs ng init
    • AngularJs ng-repeat
    • AngularJs ng-change
    • AngularJs ng-options
    • AngularJs expressions
    • AngularJs onclick
    • AngularJS ng-show
    • AngularJs ng-include
    • Scope in AngularJS
    • AngularJS ng-if
    • AngularJS Number Filter
    • AngularJS Date Filter
    • AngularJS ng-class
    • AngularJS ng-model
    • AngularJS ng-disabled
    • AngularJS Custom Filter
    • AngularJS Validation
    • AngularJS Filters
    • Controllers in AngularJS
    • AngularJS Animations
    • AngularJS Services
    • AngularJS Events
    • AngularJS Versions
    • AngularJS Directives
    • AngularJS Unit Testing
    • AngularJS with Bootstrap
    • AngularJS UI Bootstrap
    • AngularJS Routing Example
  • Interview Question
    • Angular JS Interview Questions

AngularJS ng-model

By Kinjal LodhaKinjal Lodha

AngularJS ng-model

Definition of AngularJS ng-model

AngularJS ng-model is an In-Built AngularJS directive which is the heart of angularJS application as it is used in the HTML view for binding the view into the model and gives two-way data binding. This directive is a must requirement in input, select, textarea HTML elements and can be used in form validations such as text, number, email, required, etc., validating state based on CSS classes applied on that particular element such as ng-pristine, ng-dirty, ng-touched, etc.

Syntax:

There are various HTML elements with which ng-model directive is used.

1. Using ng-model with Input Types

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Checkbox

<input type=”checkbox” ng-model=”modelValue”></input>

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,697 ratings)
  • Email

<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 directive which have been provisioned by the AngularJS framework will always be denoted with ng prefix.

As said ng-model directive is the heart of AngularJS application as it provides two-way data binding and helps in binding the view into the model. This way whenever the model value is updated in the View that gets reflected in the controller as well and hence last updated value is used for processing further in the controller. The ng-model directive will keep a watch on its reference and gets triggered whenever reference is modified, It will never check for the actual value. Ng-model gets triggered only in case when entire new object value is assigned, it won’t get triggered if a particular property of model (object or collection) is updated. The way ng-model directive works is the $watchCollection() method from angularJS keeps an eye on model value and does comparison(not deep comparison) and accordingly updates the model value. ng-model directive is executed at priority level 1 and it can also be used along with input type, select type, textarea in AngularJS.

Ng-model directive is also used to handle animations and trigger CSS properties based on model value. There are various CSS classes that are associated with model value and model animation gets triggered when these CSS classes are added or removed. Say for example if the input type is email and form validation goes invalid for email type, then ng-invalid CSS class gets triggered, this class can be used along with input type class and handled as per requirement. More such CSS classes are .ng-valid, .ng-dirty, .ng-touched, etc. It is ngAnimate that will get evaluated whenever these CSS classes are added or removed.

Another important thing to keep in my mind while using the ng-model directive is that, if the model value assigned to the ng-model directive is not already in scope then angularJS implicitly creates and adds to the existing controller scope in which the HTML element is used.

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. We have taken various HTML elements to showcase the use of the ng-model directive in the HTML template. This directive is used with different input types such as checkbox, text, tel, email, etc. and also used for displaying selected value from a dropdown and textarea. We have considered an example of an Application form which has different field and different 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 with 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 input type email with accepts only email id pattern and the input value is two way binded to ng-model emailId. If email id pattern validation fails then it won’t be reflected in model value emailId

<input type="tel" ng-model="phone"/>

This is an example of input type tel(telephone) with accepts only numbers and the input value is two way binded to 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"/>

This is an example of an input type checkbox which is two way bound to ng-model newApplicant. The value of this model variable will change every time the checkbox is selected or deselected.

<select ng-model="locationValue" ng-options="location as location.name for location in locations"></select>

This is an example of using ng-model directive with the dropdown in the HTML view. For displaying a dropdown select tag of HTML is used and to display a list of locations ng-options directive is used. The model value with store the entire location object of the selected option.

<input type="radio" name="occurrences" ng-value="role" ng-model="model.selectedRole"/>

This is an example of input type radio which is used to select any one value from a list of values. The ng-model will have the value stored in the object model and the selected name can be referred to from this object as model.selectedRole

<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 binded to ng-model additionalReq.

input[type=email].ng-invalid

Adding ng-invalid class in CSS Style helps in evaluating 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 value is invalid.

Another important feature of angularJS application and using ng-model directive in HTML view is that, as two-way binding is done and so any value modified or entered in the HTML view gets updated in the model value immediately. 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, instead, data is directly seen on the HTML view using interpolations. Refer to the output below

Output 1: Using ng-model directive with different input types, select and textarea.

AngularJS ng-model - output 1

Output 2: Input all fields with valid details

AngularJS ng-model - 2

Output 3: All value reflected in HTML view

AngularJS ng-model - output 3

Output 4: Input invalid email id

output 4

Output 5: All value except email id reflected in HTML view.

output 5

 Conclusion

ng-model is a directive in AngularJS that comes with a lot of importance and takes priority level 1 in angularJS application. This directive is used for binding the “view” to the “model” and utilizing the model value in the HTML view as well as the controller. In addition to this, it also provides the ability to perform different form validation and using CSS classes to handle different behavior of input type. Knowing where and when the ng-model will get triggered is very important. There are various different HTML tags with which this directive can be used.

Recommended Articles

This is a guide to AngularJS ng-model. Here we also discuss the definition and How the ng-model directive works in AngularJS? along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. AngularJS ng-disabled
  2. AngularJS Custom Filter
  3. AngularJS Currency Filter
  4. AngularJS Filters
Popular Course in this category
Angular JS Training Program (9 Courses, 7 Projects)
  9 Online Courses |  7 Hands-on Projects |  64+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more