articles

Home / DeveloperSection / Articles / Data Binding in Angularjs

Data Binding in Angularjs

Anonymous User4017 01-Apr-2015

Data binding is the most useful and powerful feature among any of the existing or upcoming software development technology.

Introduction:

Angularjs is actually a process that bridges a connection between the view and business logic of the application.

Basically we will see one-way and two-way data binding with respect to AngularJS applications. But before we jump to that section we will try to learn something about the scopes in AngularJS.

Scope in Angularjs:

First of all let us try to understand about scope. Scopes are a core fundamental of any AngularJS application. Since they are used all over in any AngularJS application, so it's important to know about them and their working. In AngularJS, scopes are those objects that contain functionality and the data that has to be used when rendering the view. The scopes of the application refer to the application model, so you can think of scopes as a view model.

Scopes are the source of truth for the application state. Because of this live binding, we can rely on the $scope to update immediately when the view modifies it, and we can rely on the view to Update when the $scope changes.

Functions of Scopes:
  • Provides observers to watch for all the model changes.
  • Provides the ability to propagate model changes through the application as well as outside the system to other components associated.
  • Scopes can be nested in such a way that they can isolate functionality and model properties.
  • Provides an execution environment in which expressions are evaluated.
  • There is lot of things to know about scope and we will discuss slowly on lifecycle of scope and see how internally it handles request/response in the browser in our later articles as we go deeper.
Basic Data Binding/One-Way Data Binding:

One-way data binding is an approach where a value is taken from the data model and inserted into an HTML element. There is no way to update model from view. 

AngularJS  provides some predefined data binding directives which are as
follows:

ng-bind – Binds the inner Text property of an HTML element.

ng-bind-template - Almost similar to the ng-bind directive but allows for multiple template.

ng-non-bindable - Declares a region of content for which data binding will be skipped.

ng-bind-html - Creates data bindings using the inner HTML property of an HTML element.

ng-model - Creates a two-way data binding.

Let us try to understand some of the directives programmatically which will show you how one can use in their application in the real world scenario. 

This is how our app.js file looks:

var app = angular.module('MyApp', []);

Below is our maincontroller.js and I named it as "BookStore"

app.controller("BookStore", function ($scope) {
    $scope.items = [
        { ISBN: "5674789", Name: "Asp.Net MVC", Price: 560, Quantity: 20 },
        { ISBN: "4352134", Name: "AngularJS", Price: 450, Quantity: 25 },
        { ISBN: "2460932", Name: "Javascript", Price: 180, Quantity: 15 }
    ];
 
});

And here comes our html page which will be displayed on your browser.

<htmlng-app="MyApp">
<head>
    <title>Basic Binding App</title>
    <linkhref="~/Content/bootstrap.min.css"rel="stylesheet"/>
    <scriptsrc="~/Scripts/angular.min.js"></script>
    <scriptsrc="~/Scripts/app.js"></script>
    <scriptsrc="~/Scripts/mainController.js"></script>
</head>
<body>
    <divng-controller="BookStore">
        <tableclass="table table-striped table-bordered">
            <tr>
                <td>
                    <span>Below output is produced from AngularJS's <strong>{{}}</strong> directive.</span>
                </td>
            </tr>
            <trng-repeat="item in items">
                <td>
                    <p><b>{{item.Name}}</b> is in our stock.</p>
                </td>
            </tr>
        </table>
        <tableclass="table table-striped table-bordered">
            <tr>
                <td>
                    <span>Below output is produced from AngularJS's <strong>ng-bind</strong> directive.</span>
                </td>
            </tr>
            <trng-repeat="item in items">
                <td>
                    <p><b><spanng-bind="item.Name"></span></b>is in our stock.</p>
                </td>
            </tr>
        </table>
        <tableclass="table table-striped table-bordered">
            <tr>
                <td>
                    <span>Below output is produced from AngularJS's <strong>ng-non-bindable</strong> directive.</span>
                </td>
            </tr>
            <trng-repeat="item in items">
                <td>
                    <divng-non-bindable>
                        <p><b>{{item.Name}}</b> is in our stock.</p>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

 Output:

Data Binding in Angularjs

 Two-Way Data Binding:

In simple terms two-way data binding is when the model changes, the view reflects the change, and vice versa. Two-way bindings in AngularJS are created with the ng-model directive. Practically, two-way bindings can be applied only to those elements that allow the user to provide a data value, which means the input, textarea, and select elements.

Let us now try to see how we can implement two-way binding in any application. Add a new html page as I created below:

<htmlng-app="MyApp">
<head>
    <title>Books</title>
    <linkhref="~/Content/bootstrap.min.css"rel="stylesheet"/>
    <scriptsrc="~/Scripts/angular.min.js"></script>
    <scriptsrc="~/Scripts/app.js"></script>
    <scriptsrc="~/Scripts/mainController.js"></script>
</head>
    <br/><br/>
<bodyclass="container">
    <div>
        <divng-controller="BookStore">
            <br/>
            <divstyle="padding-top: 15px;">
                <tableclass="table table-striped table-bordered">
                    <tr>
                        <td>ISBN</td>
                        <td>Name</td>
                        <td>Price</td>
                        <td>Quantity</td>
                        <td>Total Price</td>
                        <td>Action</td>
                    </tr>
 
 
                    <trng-repeat="item in items">
                        <td>{{item.ISBN}}</td>
                        <td>
                            <spanng-hide="editMode">{{item.Name}}</span>
                            <inputtype="text"ng-show="editMode"ng-model="item.Name"/>
                        </td>
                        <td>
                            <spanng-hide="editMode">{{item.Price}}</span>
                            <inputtype="number"ng-show="editMode"ng-model="item.Price"/>
                        </td>
                        <td>
                            <spanng-hide="editMode">{{item.Quantity}}</span>
                            <inputtype="number"ng-show="editMode"ng-model="item.Quantity"/></td>
                        <td>{{(item.Quantity) * (item.Price)}}</td>
                        <td>
                            <span>
                                <buttontype="submit"ng-hide="editMode"ng-click="editMode = true; editItem(item)">Edit</button></span>
                            <span>
                                <buttontype="submit"ng-show="editMode"ng-click="editMode = false">Save</button></span>
                            <span>
                                <inputtype="button"value="Delete"ng-click="removeItem($index)"/></span>
                        </td>
                    </tr>
 
                </table>
            </div>
            <br/>
            <divstyle="font-weight: bold">Grand Total: {{totalPrice()}}</div>
            <br/>
        </div>
    </div>
</body>
</html>

Now extend our controller and implement some functionalities to show items on the table and allow users to perform edit, save and delete the data on the table. Since in this application we are not using any Web Service or Web API to post data to the server so I haven’t written functionality to collect and post data to server through some Ajax request. As we go long we will try to extend application that uses some sort of Web Api to post data to server.

app.controller("BookStore", function($scope)
{
    $scope.items = [
        {ISBN:"5674789", Name: "Asp.Net MVC", Price: 560, Quantity: 20},
        {ISBN:"4352134",Name: "AngularJS", Price: 450, Quantity: 25},
        {ISBN:"2460932",Name: "Javascript", Price: 180, Quantity: 15}
    ];
    $scope.editing = false;
                               
    $scope.totalPrice = function(){
        var total = 0;
        for(count=0;count<$scope.items.length;count++){
            total += $scope.items[count].Price*$scope.items[count].Quantity;
        }
        return total;
    }
                               
    $scope.removeItem = function(index){
        $scope.items.splice(index,1);
} $scope.editItem = function(index){ $scope.editing = $scope.items.indexOf(index); } $scope.saveField = function(index) { if ($scope.editing !== false) { $scope.editing = false; } } });    }
    $scope.editItem = function(index){
        $scope.editing = $scope.items.indexOf(index);
                                                  
    }
    $scope.saveField = function(index) {
        if ($scope.editing !== false) {
            $scope.editing = false;
        }      
    }
});
Output:

Data Binding in Angularjs

 

Now let us write function to add items collected from the view to our table.

$scope.addItem = function (item) {
        $scope.items.push(item);
        $scope.item = {};
    }

To use this functionality we will need something to get input from the user. So now I will add html tags to get the input. You can see I have used ng-model="item.ISBN" and this will actually provide two-way binding facility to us.

<h2>Add New Book</h2>
            <tableclass="table table-striped table-bordered">
                <tr>
                    <td>ISBN: </td>
                    <td>
                        <inputtype="text"ng-model="item.ISBN"class="form-control"/>
                    </td>
                </tr>
                <tr>
                    <td>Name: </td>
                    <td>
                        <inputtype="text"ng-model="item.Name"class="form-control"/>
                    </td>
                </tr>
                <tr>
                    <td>Price(In Rupee): </td>
                    <td>
                        <inputtype="number"ng-model="item.Price"class="form-control"/>
                    </td>
                </tr>
                <tr>
                    <td>Quantity: </td>
                    <td>
                        <inputtype="number"ng-model="item.Quantity"class="form-control"/>
                    </td>
                </tr>
                <tr>
                    <tdcolspan="2"class="text-right">
                        <inputtype="Button"value="Add to list"ng-click="addItem(item)"class="btn btn-primary"/>
                    </td>
                </tr>
            </table>
 Output:

Data Binding in Angularjs


I am a content writter !

Leave Comment

Comments

Liked By