Home > DeveloperSection > Articles > Data Binding in Angularjs

Data Binding in Angularjs


Angular JS Angularjs Scope  Angularjs ng Repeat  Angularjs Controller 
Ratings:
0 Comment(s)
 1040  View(s)
Rate this:

Data Binding in Angularjs

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:

v  Provides observers to watch for all the model changes.

v  Provides the ability to propagate model changes through the application as well as outside the system to other components associated.

v  Scopes can be nested in such a way that they can isolate functionality and model properties.

v  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.

<html ng-app="MyApp">

<head>

    <title>Basic Binding App</title>

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

    <script src="~/Scripts/angular.min.js"></script>

    <script src="~/Scripts/app.js"></script>

    <script src="~/Scripts/mainController.js"></script>

</head>

<body>

    <div ng-controller="BookStore">

        <table class="table table-striped table-bordered">

            <tr>

                <td>

                    <span>Below output is produced from AngularJS's <strong>{{}}</strong> directive.</span>

                </td>

            </tr>

            <tr ng-repeat="item in items">

                <td>

                    <p><b>{{item.Name}}</b> is in our stock.</p>

                </td>

            </tr>

        </table>

        <table class="table table-striped table-bordered">

            <tr>

                <td>

                    <span>Below output is produced from AngularJS's <strong>ng-bind</strong> directive.</span>

                </td>

            </tr>

            <tr ng-repeat="item in items">

                <td>

                    <p><b><span ng-bind="item.Name"></span></b>is in our stock.</p>

                </td>

            </tr>

        </table>

        <table class="table table-striped table-bordered">

            <tr>

                <td>

                    <span>Below output is produced from AngularJS's <strong>ng-non-bindable</strong> directive.</span>

                </td>

            </tr>

            <tr ng-repeat="item in items">

                <td>

                    <div ng-non-bindable>

                        <p><b>{{item.Name}}</b> is in our stock.</p>

                    </div>

                </td>

            </tr>

        </table>

    </div>

</body>

</html>

 

Output:

 

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:

<html ng-app="MyApp">

<head>

    <title>Books</title>

    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />

    <script src="~/Scripts/angular.min.js"></script>

    <script src="~/Scripts/app.js"></script>

    <script src="~/Scripts/mainController.js"></script>

</head>

    <br /><br />

<body class="container">

    <div>

        <div ng-controller="BookStore">

            <br />

            <div style="padding-top: 15px;">

                <table class="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>

 

 

                    <tr ng-repeat="item in items">

                        <td>{{item.ISBN}}</td>

                        <td>

                            <span ng-hide="editMode">{{item.Name}}</span>

                            <input type="text" ng-show="editMode" ng-model="item.Name" />

                        </td>

                        <td>

                            <span ng-hide="editMode">{{item.Price}}</span>

                            <input type="number" ng-show="editMode" ng-model="item.Price" />

                        </td>

                        <td>

                            <span ng-hide="editMode">{{item.Quantity}}</span>

                            <input type="number" ng-show="editMode" ng-model="item.Quantity" /></td>

                        <td>{{(item.Quantity) * (item.Price)}}</td>

                        <td>

                            <span>

                                <button type="submit" ng-hide="editMode" ng-click="editMode = true; editItem(item)">Edit</button></span>

                            <span>

                                <button type="submit" ng-show="editMode" ng-click="editMode = false">Save</button></span>

                            <span>

                                <input type="button" value="Delete" ng-click="removeItem($index)" /></span>

                        </td>

                    </tr>

 

                </table>

            </div>

            <br />

            <div style="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;

        }      

    }

});

Output:

 

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>

            <table class="table table-striped table-bordered">

                <tr>

                    <td>ISBN: </td>

                    <td>

                        <input type="text" ng-model="item.ISBN" class="form-control" />

                    </td>

                </tr>

                <tr>

                    <td>Name: </td>

                    <td>

                        <input type="text" ng-model="item.Name" class="form-control" />

                    </td>

                </tr>

                <tr>

                    <td>Price(In Rupee): </td>

                    <td>

                        <input type="number" ng-model="item.Price" class="form-control" />

                    </td>

                </tr>

                <tr>

                    <td>Quantity: </td>

                    <td>

                        <input type="number" ng-model="item.Quantity" class="form-control" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" class="text-right">

                        <input type="Button" value="Add to list" ng-click="addItem(item)" class="btn btn-primary" />

                    </td>

                </tr>

            </table>

 

Output:


Don't want to miss updates? Please click the below button!

Follow MindStick