The Wayback Machine - https://web.archive.org/web/20241126232813/https://www.geeksforgeeks.org/angularjs-ng-model-directive/
Open In App

AngularJS ng-model Directive

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations. The various form input types (text, checkbox, radio, number, email, URL, date, datetime-local time, month, week) can be used with the ngModel directive. This directive is supported by <input>, <select> & <textarea>.

Syntax:

<element ng-model=""> 
Content...
</element>

Example 1: This example describes the basic usage of the ng-model Directive in AngularJS.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>AngularJS ng-model Directive</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>
    <style>
        body {
            font-family: Arial;
        }
        h1 {
            color: green;
        }
        .column {
            float: left;
            text-align: left;
            width: 49%;
        }
        .row {
            content: "";
            display: table;
        }
    </style>
</head>

<body ng-app="myApp" ng-controller="myController">
    <h1>GeeksforGeeks </h1>
    <h3>ng-model Directive</h3>
    <h4>Input Box</h4>
    <div class="row">
        <div class="column">
            Name
            <input type="text" ng-model="name">
            <pre> {{ name }} </pre> Checkbox
            <input type="checkbox" ng-model="check">
            <pre> {{ check }} </pre> Radiobox
            <input type="radio" ng-model="choice">
            <pre> {{ choice }} </pre> Number
            <input type="number" ng-model="num">
            <pre> {{ num }} </pre> Email
            <input type="email" ng-model="mail">
            <pre> {{ mail }} </pre> Url
            <input type="url" ng-model="url">
            <pre> {{ url }} </pre>
        </div>
        <div class="column">
            Date:
            <input type="date" ng-model="date1" 
                   (change)="log(date1)">
            <pre> Todays date:{{ date1 }}</pre> Datetime-local
            <input type="datetime-local" ng-model="date2">
            <pre> {{ date2 }} </pre> Time
            <input type="time" ng-model="time1">
            <pre> {{ time1}} </pre> Month
            <input type="month" ng-model="mon">
            <pre> {{ mon }} </pre> Week
            <input type="week" ng-model="we">
            <pre> {{ we }} </pre>
        </div>
    </div>
</body>
<script>
    var app = angular.module('myApp', []);
    app.controller('myController', function ($scope) {
        $scope.name = "Hello Geeks!";
        $scope.check = "";
        $scope.rad = "";
        $scope.num = "";
        $scope.mail = "";
        $scope.url = "";
        $scope.date1 = "";
        $scope.date2 = "";
        $scope.time1 = "";
        $scope.mon = "";
        $scope.we = "";
        $scope.choice = "";
        $scope.c = function () {
            $scope.choice = true;
        };
    });
</script>
</html>

Output:

In order to make URL and email print, we have to write a valid email/URL only then it would get printed. In the case of printing of date, and time using ngmodel, then we have to fill in all the fields in the input box. The radio button once selected won’t get deselected since, in the function of “c”, we are setting the value of choice as true. 

HTML forms using the ng-model directive: We can define ngModel in the following way by writing the below code in the app.component.html file.

<div class="form-group">
<label for="phone">mobile</label>
<form>
<input type="text"
id="phone"
ngModel name="phone"
#phone="ngModel"
placeholder="Mobile">
</form>
<pre>{{ phone.value }}</pre>
</div>

The ngModel directive stores a variable by reference, not value. Usually in binding inputs to models that are objects (e.g. Date) or collections (e.g. arrays). The phone object created has many fields which are used for validation purposes. The following is the list of classes for validation purposes:

  • ng-touched: It shows that field has been touched.
  • ng-untouched: It shows that field has not been touched yet.
  • ng-valid: It specifies that the field content is valid.
  • ng-invalid: It specifies that the field content is not valid.
  • ng-dirty:  It illustrates that the field has been modified.
  • ng-pristine: It represents that the field has not been modified yet.

Binding ngModel with getter and setter: Whenever a function is called with zero arguments then it returns a representation of the model. And when called with a parameter it sets the value. Since ngModel refers to address that is why it does not save the changed value in the object itself rather it saves it in some internal state (variable-name.value). It will be useful if we keep a practice of using getter and setter for models when there is an internal representation as the getter and setter function gets more often called as compared to the rest of the parts of the code. 

Syntax:

ng-model-options="{ getterSetter: true }"

We can add this to the input element. 

Example 2: This example describes the ng-model Directive in AngularJS, where we have bound the ngModel directive with getter and setter.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>AngularJS ng-model Directive</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
    </script>

    <style>
        body {

            font-family: Arial;
            margin-left: 45px;
        }

        h1 {
            color: green;
        }
    </style>
</head>

<body ng-app="myApp">
    <h1>GeeksforGeeks</h1>
    <h3>ng-model Directive</h3>
    <div ng-controller="myController">
        <form>
            Name 1:<input type="text" name="Name" 
                ng-model="user.name" 
                ng-model-options="{ getterSetter: true }" />
            <pre>user.name = 
                <span ng-bind="user.name()"></span>
            </pre>
            Name 2:<input type="text" name="Name1" 
                ng-model="user.name1" 
                ng-model-options="{ getterSetter: true }" />
            <pre>user.name =
                <span ng-bind="user.name1()"></span>
            </pre>
        </form>
    </div>
    <script>
        angular.module('myApp', [])
            .controller('myController', ['$scope', function ($scope) {
                name = 'GeeksforGeeks';
                name1 = "";
                $scope.user = {
                    name: function (Name) {
                        return arguments.length ? (name = Name) : name;
                    },
                    name1: function (Name1) {
                        return arguments.length ? (name1 = Name1) : name1;
                    }
                };
            }]);
    </script>
</body>

</html>

Output: Here, we have initialized name 1 by the string GeeksforGeeks and name 2 by an empty string. 

 References: https://docs.angularjs.org/api/ng/directive/ngModel



Previous Article
Next Article

Similar Reads

AngularJS ng-model-options Directive
The ng-model-options directive has the feature which helps the user to modify, within the current application, the behavior of the ngModel directives. Basically, it is in use when the user has to control the binding of a variable and an HTML form element in the scope. You can also specify the amount of waiting time for binding to happen. It could b
2 min read
AngularJS ng-show Directive
The ng-show Directive in AngluarJS is used to show or hide the specified HTML element. If the given expression in the ng-show attribute is true then the HTML element will display otherwise it hides the HTML element. It is supported by all HTML elements. Syntax: <element ng-show="expression"> Contents... </element> Parameter Value: expre
2 min read
AngularJS ng-init Directive
The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application. Syntax: <element ng-init = "expression"> ... </element>Example: This example descr
1 min read
AngularJS ng-if Directive
The ng-if Directive in AngularJS is used to remove or recreate a portion of the HTML element based on an expression. The ng-if is different from the ng-hide directive because it completely removes the element in the DOM rather than just hiding the display of the element. If the expression inside it is false then the element is removed and if it is
2 min read
AngularJS ng-dblclick Directive
The ng-dblclick Directive in AngluarJS is used to apply custom behavior when an element is clicked double. It can be used to show or hide some element or it can popup an alert or change the color of text when it is clicked twice. This means that the element's original ondblclick event will not be overridden by this directive, both will be executed.
2 min read
AngularJS ng-keypress Directive
The ng-keypress Directive in AngluarJS is used to apply custom behavior on a keypress event. It is mainly used to specify what to do when the keyboard is utilized with a particular HTML element. The order of sequence that the key is pressed is Keydown, Keypress, and keyup. It is supported by <input>, <select> and <textarea> elemen
2 min read
AngularJS ng-keydown Directive
The ng-keydown Directive in AngluarJS is used to apply custom behavior on a keydown event. This directive will not be overridden by the element's original onkeydown event. Both the onkeydown event & the ng-keydown Directive will be executed. It is supported by <input>, <select> and <textarea> elements. Syntax: <element ng-k
2 min read
AngularJS ng-keyup Directive
The ng-keyup Directive in AngluarJS is used to apply custom behavior on a keyup event. It is supported by <input>, <select> and <textarea> elements. Syntax: <element ng-keyup="expression"> Contents... </element> Parameter: expression: When a keypress is finished, then the followed expression will be executed.Example 1:
2 min read
AngularJS ng-href Directive
The ng-href directive is used when we have an angular expression inside the href value. If href attribute is used then the problem is that if in case the link is clicked before AngularJS has replaced the expression with its value then it may go to the wrong URL and the link will be broken and will most likely return a 404 error while ng-href direct
2 min read
AngularJS ng-focus Directive
The ng-focus Directive in AngluarJS is used to apply custom behavior when an element is focused. It can be used to show/hide some element or it can pop up an alert when an element is being focused. It is supported by <a>, <input>, <select> and <textarea> elements. Syntax: <element ng-focus="expression"> Contents...
1 min read
AngularJS ng-hide Directive
The ng-hide Directive in AngluarJS is used to show or hide the specified HTML element. If the expression given in the ng-hide attribute is true then the HTML elements hide. In AngularJS there is a predefined class named ng-hide which is used to set the display to none. Syntax: <element ng-hide="expression"> Contents... </element> Parame
2 min read
AngularJS ng-disabled Directive
In this article, we will see the AngularJS ng-disabled Directive, along with understanding its implementation through the illustrations. The ng-disabled Directive in AngularJS is used to enable or disable the HTML elements. If the expression inside the ng-disabled attribute returns true then the form field will be disabled or vice versa. It is usua
2 min read
AngularJS ng-list Directive
The ng-list Directive in AngularJS is used for separating input strings and converting them into an array of strings using a separator. By default, the comma is used as a default separator. But any custom separator can be used as the value of the ng-list directive. Syntax: <element ng-list="delimiter"> Contents... </element> The value o
1 min read
AngularJS ng-mouseup Directive
The ng-mouseup Directive in AngularJS is used to apply custom behavior when a mouseup event occurs on a specific HTML element. It can be used to show a popup alert when the mouse button is pressed. The order of a mouse click is Mousedown, Mouseup, Click. It is supported by all HTML elements. Syntax: <element ng-mouseup="expression"> Contents.
2 min read
AngularJS ng-mousedown Directive
The ng-mousedown Directive in AngularJS is used to apply custom behavior when mousedown event occurs on a specific HTML element. It can be used to show a popup alert when the mouse button is pressed down. It is supported by all HTML elements. Syntax: <element ng-mousedown="expression"> Contents... </element> Parameter: expression: When
1 min read
AngularJS ng-maxlength Directive
The ng-maxlength Directive in AngularJS is used to set the maximum length for an input field i.e it adds the restriction for an input field. It is different from maxlength attribute in HTML because the former prevents users from exceeding the limit whereas the later doesn't do that. It will make the form invalid if the input limit exceeds it. Synta
2 min read
AngularJS ng-minlength Directive
The ng-minlength Directive in AngularJS is used to set the minimum length for an input field i.e it adds the restriction for an input field. It is different from minlength attribute in HTML because the former prevents users from entering less than the specified limit whereas the later doesn't do that. It makes the form invalid if the entered input
2 min read
AngularJS ng-mouseover Directive
The ng-mouseover Directive in AngularJS is used to apply custom behavior when a mouseover event occurs on a specific HTML element. It can be used to show a popup alert when the mouse moves over a specific element. It is supported by all HTML elements. Syntax: <element ng-mouseover="expression"> Content... </element>Parameter value: expr
2 min read
AngularJS ng-copy Directive
The ng-copy Directive in AngularJS is used to specify the custom behavior functions during the copy of the text in input text fields. It can be used when we want to call a function that will be triggered when the text is copied from the input field. It is supported by all input elements. The element's original oncopy event will not be overridden wi
2 min read
AngularJS ng-cut Directive
The ng-cut Directive in AngularJS is used to specify the custom behavior functions when the text in input fields is cut. It can be used when we want to call a function that will be triggered when the text is cut from the input field. It is supported by all input elements. Syntax: <element ng-cut="expression"> Contents... </element>Param
2 min read
AngularJS ng-click Directive
The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can pop up an alert when the button is clicked. Syntax: <element ng-click="expression"> Contents... </element>Parameter Value: expression: It specifies when the particular element is clicked the
2 min read
AngularJS ng-controller Directive
The ng-controller Directive in AngularJS is used to add a controller to the application. It can be used to add methods, functions, and variables that can be called on some event like click, etc to perform certain actions. Syntax: <element ng-controller="expression"> Contents... </element> Parameter value: expression: It refers to the na
2 min read
AngularJS ng-checked Directive
The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked. Syntax: <input type="checkbox|radio" ng-checked="expression"> Conte
2 min read
AngularJS ng-change Directive
The ng-change Directive in AngularJS is used whenever the value of an input element changes. The expression is evaluated immediately whenever there is a change in the input value. It requires an ng-model directive to be present. It is triggered whenever there is any single change in the input. It can be used with input elements like <input>,
2 min read
AngularJS ng-bind Directive
The ng-bind Directive in AngularJS is used to bind/replace the text content of any particular HTML element with the value that is entered in the given expression. The value of specified HTML content updates whenever the value of the expression changes in the ng-bind directive. Syntax: <element ng-bind="expression"> Contents... </element
2 min read
AngularJS ng-blur Directive
The ng-blur Directive in AngularJS is fired when an HTML element loses their focus. It doesn't override with element's original onblur event i.e. both the ng-blur expression and original onblur event will execute. Syntax: <element ng-blur="expression"> Contents... </element>Parameter: expression: It refers to the variable or the express
1 min read
AngularJS ng-app Directive
The ng-app Directive in AngularJS is used to define the root element of an AngularJS application. This directive automatically initializes the AngularJS application on page load. It can be used to load various modules in AngularJS applications. The ng-app directive declares only once in the HTML document. In case if it is declared more than once th
1 min read
AngularJS ng-non-bindable Directive
The ng-non-bindable Directive in AngularJS is used to specify that the specific content of HTML should not be compiled i.e the contents should be ignored by AngularJS. It can be used when we want to display code snippets instead of compiled output. Syntax: <element ng-non-bindable> Contents... </element> Example 1: This example uses ng-
1 min read
AngularJS ng-open Directive
The ng-open Directive in AngularJS is used to specify the open attribute of the specified HTML element. If the expression inside the ng-open directive returns true then the details will be shown otherwise they will be hidden. Syntax: <element ng-open="expression"> Contents... <element> Parameter: expression: If the expression returns tr
1 min read
AngularJS ng-options Directive
The ng-options Directive in AngularJS is used to build and bind HTML elements with options to a model property. It is used to specify <options> in a <select> list. It is designed specifically to populate the items on a dropdown list. This directive implements an array, in order to fill the dropdown list. It is supported by the <selec
2 min read
three90RightbarBannerImg