Data binding in AngularJS

Nov 25, 2014

In this short blog post we will start exploring the data binding features of AngularJS framework. In the previous blog post we saw step by step tutorial on building our first AngularJS application. In that post we saw the one side data binding operation coming form source [Controller] to destination [UI]

But AngularJS is designed with two day data binding. Meaning if you have to take the updated data form the User Interface back to the source, you can do that pretty easily. In fact, that's exactly we are going to do in this blog. Following is the diagram of two way data binding for those of you who are visual learner.

Data Binding With AngularJS

Before we begin, I assume you have basic idea about how AngularJS framework works and if not you have at least follow my previous blog post. We will continue expanding on the same sample.

Updating the HTML

In the previous post we saw how to bind data from the Source to Destination. Meaning from the Model to the View. Now let's modify the View to have an input box and whatever is typed in the Input box we will try to bind that back to the Model.

For that, let's go ahead and add the Text Input box on the HTML as below.

Data Binding With AngularJS

Notice the ng-model directive on the element. This essentially tells the Angular that the value of this input box should be automatically bound to the Model property defined for the controller of the current scope.

And if you looks one line above the input box you will see that the controller that is responsible for handling this part of HTML is DemoController. That means if our controller has property named name in the message object, it will be automatically populated with value of the input box. And we will not have to write a single line of code for this data binding to happen.

Also notice how I am binding the same property into the P element. So what I am essentially doing is taking value from an input box, binding it to model and mode is binding the value back to my paragraph.

Changes to Controller

Not major changes here. All I am doing is changing the property name form text in previous blog to name.

Data Binding With AngularJS

Go ahead and view the page in browser. You will see that initial binding from Model to View is working fine.

Data Binding With AngularJS

Try changing the value of the input box and you notice the message in the P tag updating instantly without us writing any JavaScript. Pretty cool, right ?

Data Binding With AngularJS

Okey, now that we have very basic understanding of data binding, we will start exploring some more basic topics of AngularJS.