×

Html & Html5

The World's best Software Development Study Portal

AngularJS Data Binding


  • Data binding is the synchronization between the model and the view.

  • The HTML container where the AngularJS application is displayed, is called the view.

  • The data model is a collection of data available for the application.
  • For example




    For Example:

         	<div ng-app="myApp" ng-controller="myCtrl">
            Name: <input ng-model="firstname">
             <h1>{{firstname}}</h1>
             </div>
             <script>
             var app = angular.module('myApp', []);
             app.controller('myCtrl', function($scope) {
             $scope.firstname = "IT training classes";
             $scope.lastname = "welcomes you";
             });
             </script>
             
    Output
    Name: IT training classes




    Two-Way Data Binding:


    Two-way binding gives your app a way to share data between a component class and its template. The binding goes both ways. If the user changes the value inside the input field, the AngularJS property will also change its value.

    When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.

    Basics of two-way binding:

    Two-way binding does two things:

    1.Sets a specific element property.

    2.Listens for an element change event.

    Angular offers a special two-way data binding syntax for this purpose,[()].

    The [()] syntax combines the brackets of property binding,[], with the parentheses of event binding,().

    The ng-init directive can be used to initialize variables in AngularJS application.



    When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well. Lets see an example:

           <div ng-app="myApp" ng-controller="myCtrl">
           Name: <input ng-model="firstname">
           <h1>{{firstname}}</h1>
           </div>
    
           <script>
           var app = angular.module('myApp', []);
           app.controller('myCtrl', function($scope) {
           $scope.firstname = "IT training classes";
           $scope.lastname = "welcomes you";    
           });
           </script>
    
             
    Output

    Name:

    {{firstname}}



    Important Points:


    =>The binding goes both ways called Two-Way Data Binding If the user changes the value inside the input field, the AngularJS property will also change its value.

    =>The ng-model directive can provide type validation for application data (number, e-mail, required).

    =>The ng-model directive can provide status for application data (valid, dirty, touched, error).

    =>The ng-model directive provides CSS classes for HTML elements, depending on their status.