Learn ngmodel in AngularJS – How to use ng-model Directive?
Free Angular course with real-time projects Start Now!!
After MVC Architecture, we are going to discuss ngmodel in Angular JS. Model is a component of MVC architecture, which we can use to create an angular application. In this ngmodel tutorial, we will study ng-model in AngularJS for binding input control with application data, for application status, for validation, for complex models, and with getter and setter.
Angular JS is a framework that appears simple at first, but start to use it to develop an application even just a bit complex and you will see a lot of questions but can’t answer them. AngularJS, a good framework that it leaves you with enough flexibility. But flexibility also means that you need to figure out on your own how to solve this issue in angular?
So, are you ready to learn ngmodel in AngularJS?
1. What is AngularJS Model?
Model is a component of MVC architecture, which we can use to create an angular application.
The request made by the user from view part is managed in model part.
Suppose you are entering text in the input field and the text you are entering is displaying on the same page since it is a single page application. It is made possible because the coding is done in the model part. Therefore, we can connect the model part and view part with each other.
2. ngmodel in AngularJS
The ngmodel in AngualrJS is directive to bind the value of an HTML control (input, select, text area) or input field to an application data (variables) created in AngularJS. It ensures the synchronization between a model part and view part.
The various purposes of ngmodel are as follows:
- View is bind with a model using ng-model directive, which other directives such as input, select or text area will require.
- Validations behaviour can be provided using it.
- We can use ngmodel to keep the state of control.
- ngmodel is responsible for registering the control with its parent form.
Example-Â You are registering on a site and the owner of the site wants your data to get saved in a database. But he is displaying a single registration form page to a user. At that time, ngmodel in AngularJS can be used to map the value of controls and data model.
NOTE: Directives Executes At Priority Level 1.
i. ngmodel for binding input control with application data
For binding the value of various input controls with the application data of our application, we can use the ngmodel directive.
Various input controls with which we can use ngmodel directives are:
a. Input
- Text
- Checkbox
- Radio
- Number
- URL
- Date
- Datetime-local
- Time
- Month
- Week
b. Select
c. Text area
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <div ng-app="demoone" ng-controller="myCtrl"> Enter Text: <input ng-model="name"> <h1>You Entered: {{name}}</h1> </div> <script> var one = angular.module('demoone', []); one.controller('myCtrl', function($scope) { $scope.name = "Angular"; }); </script> <p>Change the text inside the input field, and you will see according to the text inside input field, the text in the header changes.</p> </body> </html>
Output:
Enter Text: Angular
You Entered: Angular
Change the text inside the input field, and you will see according to the text inside the input field, the text in the header changes.
Recommended reading – AngularJS Modules
ii. The ngmodel in AngularJS for application status
Status for application, data can be provided using ngmodel directive.
Various application status with which we can use ng-model directive are:
- ng-valid: Use to check the model is valid or not. It returns a true value if, a model is valid.
- ng-invalid: Use to check that the model is invalid or not. It returns a true value if, a model is invalid.
- ng-pristine: It returns a true value if the user hasn’t interacted with control yet.
- ng- dirty: It returns a true value if the user has already interacted with control.
- ng-touched: It will return a true value if the control blurs or the control focus.
- ng-untouched: It will return a true value if the control hasn’t been blurred or the control has not lost focus yet.
- ng-pending:Â Use to test, if any $asyncValidators are unfulfilled or pending on the whole form or a specific input element.
We will discuss more in article form validations.
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <form ng-app="" name="value" ng-init="myText = '[email protected]'"> Enter Email: <input type="email" name="value" ng-model="myText" required> <p>change the e-mail address, and try to change the status.</p> <h1>Status</h1> <p>Valid: {{myForm.value.$valid}} (if true, the value meets all criteria).</p> <p>Dirty: {{myForm.value.$dirty}} (if true, the value has been changed).</p> <p>Touched: {{myForm.value.$touched}} (if true, the field has been in focus).</p> </form> </body> </html>
Output:
Enter Email: [email protected]
Change the e-mail address, and try to change the status.
Status
Valid: (if true, the value meets all criteria).
Dirty: (if true, the value has been changed).
Touched: (if true, the field has been in focus).
ii. ng-model for validation
It provides type validation for application data.
<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> <form ng-app="" name="myFirstForm"> Enter Email: <input type="email" name="value" ng-model="text"> <span ng-show="myFirstForm.value.$error.email">Not a valid e-mail address</span> </form> <p>Enter your e-mail address. Angular will display a message if the address is not an e-mail.</p> </body> </html>
Output:
Enter Email:
Enter your e-mail address. Angular will display a message if the address is not an e-mail.
Suppose you entered a text angular in the input field the output will be
Enter Email: Angular (Not a valid e-mail address)
Enter your e-mail address. Angular will display a message if the address is not an e-mail.
Suppose you entered a text [email protected] in the input field the output will be:
Enter Email: [email protected]
Enter your e-mail address. Angular will display a message if the address is not an e-mail.
iv. Complex models
ng-model directive watches the model by reference, not value by default. This is important to know, in case you are binding inputs to models that are objects such as date or collections or arrays. ngmodel in AngularJS will not be notified if only properties of the object or collection change and so the input will not be re-rendered as the value is not changed. To display the input as per the changes user made in properties of object or collection, a model must be assigned an entirely new object or collection before a re-rendering will occur.
Some directives have an option to use a $watchCollection method on the model expression. This method does a shallow comparison. It means changing properties deeper than the first level of the object (or only changing the properties of an item in the collection if it’s an array). It will still not trigger a re-rendering of the model.
v. ng-model with getter and setter
It is a function used to return a representation of the model when called with zero parameter or argument. And when called with an argument or parameter sets the value internal state of a model. It is useful to use getter and setter for models when there is an internal representation of the model that is different from what models expose to view part.
Syntax:
ng-model-options="{ getterSetter: true }"
We can add above syntax to an element that has ngmodel attached to it. You can add this to form too which will enable this behaviour for all <input>s within it.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Getter Setter Example</title> <script src="//code.angularjs.org/snapshot/angular.min.js"></script> <script src="app.js"></script> </head> <body ng-app="myapp"> <div ng-controller="controllerexample"> <form name="myForm"> <label>Enter Name: <input type="text" name="value" ng-model="user.name" ng-model-options="{ getterSetter: true }" /> </label> </form> <pre>name Of user= <span ng-bind="user.name()"></span></pre> </div> </body> </html>
Output:
Enter Name:
name Of user=
When you enter some text in the input field the output will be:
Enter Name: Ram Kumar
name Of user= Ram Kumar
3. Conclusion
In the above article, we discussed ngmodel in AngularJS, a model part of MVC architecture in a detailed manner. But the primary focus of the model is to bind the data with view part. We can use the ng-model directive for binding. Furthermore, we studied various input controls where the ng-model directive is used. Hope you liked our explanation. Still, if you have a query, feel free to ask in the comment tab.
Did we exceed your expectations?
If Yes, share your valuable feedback on Google