Friday, March 25, 2016

two way data binding in angular.js using ng-model

In angular js, we have two directives ng-model and ng-bind. For a novice like me, both of them may sound same until they are explored in depth. However, they are not. The big difference between the two is that ng-model supports two way binding and ng-bind does not.

To understand the two-way binding, suppose we have an input type control. We need to display the value entered in the control in any span or div tag, as the value is getting changed i control. Then we normally use jQuery or some event like 'key-up', to display the value, as it get's changed. However, in angular js, we can easily do this using the ng-model directive. 

Let's create a small example to understand this. First we create an input type control and bind it with a model property named "sampleValue", using the ng-model directive. 

<input type="text" ng-model="sampleValue">

Next, we will use the angular expressions to display the value in the span tag. So our code will look like:

You have entered: <span ng-bind="sampleValue"></span>

That's it, we are done. Run the application enter any value in the input type and see the value changes in the span tag also. See the image below:

So the complete code will look like the below:

!DOCTYPE html>
<html xmlns="">
    <script src=""></script>
    <div ng-app="">
            <legend>ng-Model Example</legend>
            <h4>Display the model data changed in the SPAN tag, using ng-Model</h4>
                Enter a value:
            <input type="text" ng-model="sampleValue">
            <p>You have entered: <span ng-bind="sampleValue"></span></p>
        <br />

Hope you liked reading it....Happy coding...!!!

No comments:

Post a Comment