Understanding the basics of Data Binding in AngularJS

Data-binding in Angular applications is about automatic synchronization of data between the model and view components. AngularJS implements data binding in a way that lets you treat model as the single source of truth in your application. When the model changes, the view reflects the change and vice versa.

Before we explore how data binding works in AngularJS, lets understand how it works in classic templating systems.

One-Way Data Binding

Most templating systems bind data in only one direction: As shown in the image below, they merge template and model components together into a view. After the merge occurs, changes to the model or related sections of the view are NOT automatically reflected in the view. What’s even worse is that any changes the user makes to the view are not reflected in the model. This means that the developer has to write code that constantly syncs the view with the model and the model with the view.

Two-Way Data Binding

Angular templates work differently. First the template (which is the uncompiled HTML along with any additional markup or directives) is compiled on the browser. The compilation step produces a live view. Any changes to the view are immediately reflected in the model, and any changes in the model are propagated to the view. The model is the single-source-of-truth for the application state, greatly simplifying the programming model for the developer. You can think of the view as simply an instant projection of your model.

Because the view is just a projection of the model, the controller is completely separated from the view and unaware of it. This makes testing a snap because it is easy to test your controller in isolation without the view and the related DOM/browser dependency.


Follow this plunker to play with AngularJS two-way data binding https://plnkr.co/edit/fIhoURVXFaBChxrww73P?p=preview