What is AngularJS Models

Introduction

This article demonstrates nature and behavior of an AngularJS directive ng-model and starts with introduction of this directive. After that, we’ll understand it using  a set of examples. At last but not least, it’s 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 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 value of text box using AngularJS APIs.

In the above example, 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 controller to “Satyendra Mishra”. This value is ultimately set as text box value.

Hence the output is as below:

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

 Two way behavior

It’s reverse is also possible. i.e.

If we set value of text box then provided value is automatically assigned to AngularJS model variable which can be fetched using AngularJs – Expression or ng-bind Directive.

Let’s see it’s example as well:

On page load, we’ll see  the output as below:

But as soon as we change value in text box, statement “Your name is ______” is also changed. See the screenshot below

Summary

In this article, I discussed about ng-model and it’s two way behavior. We learnt, how does data flow from HTML to AngularJS and vice versa.

 

Be  Connected…

Satyendra Mishra

Leave a Reply

Your email address will not be published. Required fields are marked *