Click here to Skip to main content
13,732,461 members
Click here to Skip to main content
Add your own
alternative version

Stats

166.6K views
5.1K downloads
55 bookmarked
Posted 17 Aug 2014
Licenced CPOL

Part 2: Data Binding In AngularJS

, 21 Apr 2018
Rate this:
Please Sign up or sign in to vote.
In this article, we will try to understand Data Binding in AngularJS

Introduction

In the previous article on Part 1: Introduction to AngularJS, we have seen some introductory material and few directives with the help of a sample application to understand basics of AngularJS. So I think we are somewhat familiar about AngularJS and now it’s time to go more on it. Let’s proceed with this part of the tutorial where we will try to understand the most basic and impressive feature of AngularJS, i.e., Data Binding.

Background

Data binding is the most useful and powerful feature among any of the existing or upcoming software development technologies. It 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.

Scopes In Angular World

First of all, let us try to understand about scope. I left this topic in our previous article so let's continue with this because this has a lot to do with AngularJS applications. Scopes are a core fundamental of any AngularJS application. Since they are used all over in any AngularJS application, 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

  1. Provides observers to watch for all the model changes
  2. Provides the ability to propagate model changes through the application as well as outside the system to other components associated
  3. Scopes can be nested in such a way that they can isolate functionality and model properties
  4. Provides an execution environment in which expressions are evaluated

There are a 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 them in their application in the real world scenario. I have created a module in my previous article Part 1: Introduction to AngularJS and I am using the same. I will also be extending the controller from the same.

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>
      <script src="angular.min.js"></script>
      <link rel="stylesheet" type="text/css" href="main.css" />
      <script src="app.js" type="text/javascript"></script>
      <script src="maincontroller.js" type="text/javascript"></script>
   </head>
   <body>
      <div ng-controller="BookStore">
         <table class="mytable">
            <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="mytable">
            <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="mytable">
            <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>

The above example illustrates about 2 directives which are used for Data Binding, viz., ng-bind and ng-non-bindable. We will also see ng-model in the next section when we will talk about two-way binding in AngularJS. I have not used ng-bind-template and ng-bind-html but we will get into it when we will come to learn about templating stuff in AngularJS.

This is the final output when you run the BasicBinding.html.

From the output, you can see when we used {{ }} the output is as expected since it is AngularJS's default way of handling model binding. In the second section, we used data binding directive ng-bind and the third one we used is ng-non-bindable which allows us to skip data bind to that particular section where it is defined. Also there is ng-repeat-directive which helps us to iterate throughout the collection. The collection that I used can be implemented with the help of some sort of Web-Api calls which will provide some JSON data that you can directly use it to bind.

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>
 <script src="angular.min.js"></script>
    <link rel="stylesheet" type="text/css" href="main.css" />
    <script src="app.js" type="text/javascript"></script>
    <script src="maincontroller.js" type="text/javascript"></script>
</head>
<body>
<div>
        <div ng-controller="BookStore">
            <br />
            <div style="padding-top:15px;">
            <table border="1" class="mytable">
                    <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 along, 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;
        }       
    };         
    };
	}
	);

Now let us write a 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>
<div style="border: 1px solid blue;">
   <table>
      <tr>
         <td>ISBN: </td>
         <td>
            <input type="text" ng-model="item.ISBN" />
         </td>
      </tr>
      <tr>
         <td>Name: </td>
         <td>
            <input type="text" ng-model="item.Name" />
         </td>
      </tr>
      <tr>
         <td>Price(In Rupee): </td>
         <td>
            <input type="number" ng-model="item.Price" />
         </td>
      </tr>
      <tr>
         <td>Quantity: </td>
         <td>
            <input type="number" ng-model="item.Quantity" />
         </td>
      </tr>
      <tr>
         <td colspan="2">
            <input type="Button" value="Add to list" ng-click="addItem(item)" />
         </td>
      </tr>
   </table>
</div> 

We are now done with the code. It's time to see in the end how our application looks like. So here it is the result where you can perform the CRUD operations.

NOTE: There are no validations or any error checks. I intentionally left that because we will see all this when we reach the Validations part of AngularJS tutorial series, i.e., Part 4.

Points of Interest

Now we are known to Data Binding approach that AngularJS follows and we have seen in the sample application how we can implement it in the application to perform basic CRUD operations. I hope you have learned something worthwhile from this part of the tutorial. You can download the complete application code and run it on your own.

In the next part of the tutorial series, we will be looking into:

  • Eventing in AngularJSAngularJS Part 3:
  • AngularJS Part 4: Validation
  • AngularJS Part 5: Serialization
  • AngularJS Part 6: Templating
  • AngularJS Part 7: Modules
  • AngularJS Part 8: Dependency Injection
  • AngularJS Part 9: Automated Testing
  • AngularJS Part 10: SPA Routing/History
  • AngularJS Part 11: Directives- A feature that AngularJS provides
  • AngularJS Part 12: CSS integration to create polished interfaces

History

  • 17-August-2014: First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

NitinShrivastava
Software Developer (Senior)
India India
Started my career as a Web developer in C#, Asp.Net. Later on worked with MVC, Silverlight, WPF, WCF and Windows Phone 8 development. Also worked on SSRS for the reporting purposes. Keen to learn on latest technologies. Recently worked with backbone.js and AngularJS. Now working with Azure and angular 6 with .net core.

http://nitinvshrivastava.wordpress.com

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionPart 3: Eventing in AngularJS Pin
TomCat 22-Apr-18 22:58
memberTomCat 22-Apr-18 22:58 
QuestionCSS link Pin
8-Jun-17 3:39
member8-Jun-17 3:39 
Questionquestion about angular directive ng-app Pin
3-May-17 1:11
member3-May-17 1:11 
QuestionAngular JS Pin
rajat kpatel22-Mar-17 20:46
memberrajat kpatel22-Mar-17 20:46 
QuestionPlease send links for tutorial 3-10. Pin
Prasad Anka13-Dec-16 21:08
memberPrasad Anka13-Dec-16 21:08 
QuestionPart 3 Pin
An2dSingh20-Nov-16 20:33
memberAn2dSingh20-Nov-16 20:33 
QuestionPart 2: Data Binding In AngularJS[^] Pin
Hi_Ren18-Nov-16 0:30
memberHi_Ren18-Nov-16 0:30 
PraiseVery good Article and Content Pin
Member 373016110-Nov-16 1:05
memberMember 373016110-Nov-16 1:05 
QuestionComment Pin
3-Nov-16 22:29
member3-Nov-16 22:29 
Questionnext link Pin
30-Oct-16 7:12
member30-Oct-16 7:12 
QuestionPart 2: Data Binding In AngularJS[^] Pin
30-Oct-16 7:09
member30-Oct-16 7:09 
SuggestionPart 2: Data Binding In AngularJS Pin
30-Oct-16 7:00
member30-Oct-16 7:00 
Generalnice article Pin
myabcd16-Sep-16 0:42
membermyabcd16-Sep-16 0:42 
QuestionI don't see any links for tutorial 3-10. Pin
29-Aug-16 21:46
member29-Aug-16 21:46 
QuestionNeed Link for 3-10 Pin
raj kumarpandey29-Aug-16 11:46
memberraj kumarpandey29-Aug-16 11:46 
PraiseAmazing Pin
raj kumarpandey29-Aug-16 11:03
memberraj kumarpandey29-Aug-16 11:03 
Questionwhere is the other parts of articles from 3 to 10............. Pin
venkatkts18-Aug-16 4:02
membervenkatkts18-Aug-16 4:02 
QuestionAngularJS part 1 & 2 Pin
venkatkts18-Aug-16 4:00
membervenkatkts18-Aug-16 4:00 
QuestionAwesome Pin
12-Aug-16 23:27
member12-Aug-16 23:27 
Question$Index Pin
27-Jul-16 7:49
member27-Jul-16 7:49 
QuestionPlease provide next articles also .. Pin
venubattini14-Jul-16 3:37
membervenubattini14-Jul-16 3:37 
QuestionAwesome article Pin
Member 373367912-Jun-16 16:58
memberMember 373367912-Jun-16 16:58 
QuestionPlease provide the next tutorial's part Pin
Member 113309328-May-16 22:44
memberMember 113309328-May-16 22:44 
AnswerRe: Please provide the next tutorial's part Pin
Mukesh_B22-May-18 4:47
memberMukesh_B22-May-18 4:47 
QuestionAngularjs Pin
14-Apr-16 15:49
member14-Apr-16 15:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180920.1 | Last Updated 21 Apr 2018
Article Copyright 2014 by NitinShrivastava
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid