Sunday, October 9, 2016

AngularJS - Data Binding

Data Binding:
  • Data binding in AngularJS is the synchronization between the model and the view. 
  • Model - AngularJS applications usually have a model. The model is a collection of data available for the application.
  • View - The HTML container where the AngularJS application is displayed, is called the view
  • The view has access to the model, and there are several ways of displaying model data in the view
    • You can use the ng-bind directive, which will bind the innerHTML of the element to the specified model property:
    • You can also use double curly braces {{ }} to display content from the model.
    • You can also use ng-modelThe ng-model directive can be used with any of these three html elements: input, select, textarea
  •  You can use ng-model directive for providing a two-way binding between the model and the view on HTML controls (input, select, textarea).
One-way data binding:

Most of the templating systems merge template & model into a view. After the merge occurs, the changes in the model or related sections of the view  are not automatically reflected in the view. This means developer will have to write code that constantly sync the view with model and model with view.

What is two-way Binding?
This is to do with the synchronisation between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well. This happens immediately and automatically, which makes sure that the model and the view is updated at all times. Directive ng-model is being used for implementing the two way binding between the view and the model. 


First Template (which is the uncompiled HTML with additional markup & directives) is compiled on the browser. The compiled step produces the view. Any changes to model is reflected in view and vice versa.

What is ng-model directive?
Whenever the model changes the binding expression makes sure that the data gets updated in the view. When view changes the model should be updated automatically that's exactly is the purpose is the ng-model directive. Directive ng-model updated the model when the view changes.
Example:
var myApp = angular.module('myApp', [])
                                         .controller('myController', function($scope){
                                                 var message = 'Hello World!';
                                                 $scope.message = message;
                                          });
Using this controller:
     <div ng-controller='myController'>
              <div>
                    <input type='text' ng-model = 'message' />
              </div>                   
              <div>
                   {{message}}
              </div>             
    </div>

The ng-model directive can hold any data including complex objects.

No comments:

Post a Comment