Two way data binding in angular js

Two way data binding in angular js

Data binding is a feature that you might have heard of in javascript. It is one of the core principles of javascript.

What is data binding?

Data binding in general means that changes in the property of data leads to changes in UI.

Data binding in angular js can be explained in the following example:

  1. Here the model data is bound to the $scope object.
  2. This scope object is assigned a property ‘displayVariable’ in the controller which is available in the view.
  3. This model data is bound to the html content using the angular binding expression “{{}}” on displayVariable.  Any changes made to ‘displayVariable’ in the controller will be reflected in the view.This is one way data binding in which any changes you make to the model  data will be reflected in the html.

 

Two way data binding:

Now we know what a one-way data binding is. Angular provides a powerful feature of two-way data binding. You have seen that the model can modify the html view. Similarly any changes to the bound view can modify the model as well in angular js. This concept is known as two-way data binding.

Take a look at the example below to give you a better idea:

This is a very simple example which demonstrates two-way data binding in angular js.

  1. Like the previous example we are passing the initial data to the view by binding it to a $scope object property ‘textContent’.
  2. In the view we are using this value to populate the text box by using the ng-model directive.
  3. At the same time we are displaying the model data by using {{}}
  4. Try editing the text box and you will see that the corresponding change is seen in the data displayed in the view. This indicates that you are modifying the model data from the view that is text box in this case.
  5. Hence we have achieved two-way data binding in angular js wherein any changes in the model data affects the view and any changes you make in the view affects the model data.

Let us take a look at another example where we will use the concept of two-way data binding to build a todo list in angularjs

  1. Here the $scope property is populated by an object of data that contains an array of list item with the name and status of each
  2. This is used to populate the checkboxes. The status is used to decide whether the checkbox should be pre selected or not.
  3. When you toggle the checkbox it in turn changes the model data. Thus this is two way data binding again where the changes in model data affects the view and the changes in the view affects the model data.

I hope this post helped you understand the basics of two way data binding in angular js.

Comments are closed.