How to use “ng-model” in AngularJS with EXAMPLES

What is ng-model in AngularJs?

ng-model is a directive in Angular.JS that represents models and its primary purpose is to bind the “view” to the “model”.

For example, suppose you wanted to present a simple page to the end user like the one shown below which asks the user to enter the “First name” and “Last name” in textboxes. And then you wanted to ensure that you store the information that the user has entered in your data model.

You can use the ng-model directive to map the text box fields of “First name” and “Last Name” to your data model.

The ng-model directive will ensure that the data in the “view” and that of your “model” are kept in sync the whole time.

                               can be entered into the text box.

                           3.The ng-model attribute maintains the state of the control (By state, we mean that the control and the data is bound to be always kept in sync. If the value of                                our data changes, it will automatically change the value in the control and vice versa)

How to use ng-model

1) Text Area

The text area tag is used to define a multi-line text input control. The text area can hold an unlimited number of characters, and the text renders in a fixed-width font.

So now let’s look at a simple example of how we can add the ng-model directive to a text area control.

In this example, we want to show how we can pass a multiline string from the controller to the view and attach that value to the text area control.

  • It can be clearly seen that the value assigned to the pName variable is “Guru99”
  • Since the first check value is “true” it passed, the checkbox is marked for the “Controllers” checkbox. Likewise since the second value is false, the checkbox is not marked for the “Models” checkbox.

3) Select element form Dropdown

The ng-model directive can also be applied to the select element and be used to populate the list items in the select list.

Let’s look at an example of how we can use the ng-model with the select input type.

Here we will have a text input type which will have the name of “Guru99” and there will be a select list with 2 list items of “Controller” and “Models”.

  1. The ng-model directive is used to attach the member variable called “Topics” to the select type control. Inside of the select control, for each of the options, we are attaching the member variable of Topics.option1 for the first option and Topics.option2 for the second option.
  2. Here we are defining our Topics array variable which holds 2 key-value pairs. The first pair has a value of “Controllers” and the second has the value of “Models”. These values will be passed to select input tag in the view.

    If the code is executed successfully, the following Output will be shown.