So, Scope is a JavaScript object which is available in both View and Controller.
Data binding is data synchronization between View and data model. We have seen in the previous article that AngularJS applications have data model which is a collection of data for the application view and a View is our HTML which displays the data.
Data binding is the concept or way of data traveling in the AngularJS applications. In AngularJS, the data binding defines how the data will be passed from viewing our HTML page to its business logic, or we can say from View to AngularJS functions which reside in Controllers or bind data at the same View also.
Data binding is the concept of automatic synchronization of data between View and the Model. View access model can display the model data on the View in several different ways. We can use ng-bind directive which binds innerHTML of an element.
e.g. <p ng-bind="firstName"> </p>
Or
We can use double brackets to display firstName model property value.
e.g. {{ firstName }}
Or
We can use ng-model directive to bind the model property to HTML element.
e.g. <input type="text" ng-model="firstName">
<p ng-model="firstName"> </p>
So we have seen above that we can bind a model property to HTML content in three ways, then there should be some difference among them.
Yes, there is; and the difference is in the concept of data binding. Actually, AngularJS provides two types of data binding.
- One way data binding.
- Two way data binding.
One way data binding
We have already used one way data binding in the above explanation and in our previous day’s articles in demos and examples. One way data binding is generally used is to display data on the view.
ng-bind directive and {{ }} provides the one way data binding to display data on the view in the angular JS application.
Below are the examples of the one way data binding:
e.g.
- {{ firstName }}
- <p ng-bind="firstName"> </p>
Bind model value with html element using data binding but if we change that html element it will not update value in model, it is one way binding and not synchronization between model and view.
Two way data binding
Two way data binding is the synchronization process between model and view in angular JS applications.
When value is changed in the model it reflects in the view and when value is changed in the view it also updates in model and this process happens automatically. So we always get updated and up to date model and view without writing any extra code for this.
ng-model directive provides the two way data binding between the model and the view in the angular JS application.
e.g. <input type="text" ng-model="firstName">
Find the attachment for the application demo application.
Summary
In this article, we have covered scope and data bindings and we have seen how the data travels between controller and view in AngularJS.
So, in Day Five I will cover: