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.
In the above example, we can see a text box, which is bound with AngularJS module “name”.
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
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.