Overview Of AngularJS Directive ng-model

Introduction

This blog demonstrates the nature and behavior of an AngularJS directive ng-model and starts with the introduction of this directive. Afterwards, we'll understand it, using a set of examples. At last but not least, it's a two way behavior.

The ng-model Directive

The ng-model directive binds HTML control value to AngularJS Application data. To implement this, we use a variable in AngularJS, which holds the value of HTML element (input, select, textarea) in association with ng-model directive.

Let's understand it with an example.

We have a text box, whose value is bound with AngularJS variable. In JavaScript, we'll set the value of the text box , using AngularJS API's.



In the example, shown above, we can see a text box, which is bound with AngularJS module "name".

We created a reference to AngularJS Application in JavaScript and set AngularJS variable "name" with the help of the controller to "Satyendra Mishra". This value is ultimately set as a text box value.

Hence, the output is given below-


Here, we have seen, if we set the value of AngularJS model variable, it is automatically assigned to HTML element value.

Two way behavior

Its reverse is also possible. i.e. if we set the value of the text box, the provided value is automatically assigned to AngularJS model variable, which can be retrieved, using AngularJs Expression or ng-bind Directive.

Let's see its example, given below-



On page load, we'll see the output as below,


As soon as we change the value in the text box, statement "Your name is ______" is also changed. See the screenshot, given below-



Summary

In this blog, I discussed about ng-model and it's a two way behavior. We learned how the data flows from HTML to AngularJS and vice versa.

Next Recommended Reading AngularJS (ng-model, ng-repeat)