A Simple LocalStorage Demo Using AngularJS and HTML 5

In this article you will learn how to use Browser Local Storage for storing user data using HTML5 and AngularJS.

Introduction

Many of you might already know that each browser has its own local storage. Using this functionality we can store user data in the Browser Local Storage rather than sending it to the server. This scenario is best seen in mobile applications. The application stores data in the browser's local storage when the app goes offline and sends the data to the server when it gets connected.

The data remains stored with the browser even after it is closed or the computer is restarted until the browser cache is forcefully cleared.

In this demo I will show how to save and retrieve the data from browser local storage and not detecting the connectivity when it goes online.
 
Various ways of Browser Local Storage

1. Web/Local Storage
: Used for storing name / value pairs just like cookies.  (Used in this demo). Browser Compatibility:
  • IE8+
  • Chrome 31+
  • Firefox 38+
  • Safari 7.1+
  • Pros: Good browser Support, Simple API.
  • Cons: Poor Performance on large data.
 
 
2. Web SQL Database: Used for structured databases with all the functionality and complexity of a typical SQL-powered relational database.
Firefox and IE do not support it.
  • Pros: Good Performance and robust
  • Cons: Not compatible with IE and Firefox
 
 
3. IndexedDB: Is a collection of "object stores" that you can just drop objects into. The stores are something like SQL tables, but in this case, there's no constraints on the object structure and so no need to define anything upfront.

It uses the best functionality of Local and IndexedDB.

Other ways (Session Storage, Cookies).
  • Pros: Good Performance, decent browser Support.
  • Cons: Complex API
 

Getting Started
  1. Create a new Empty Web Project in Visual Studio.

  2. Install AngularJs from Nuget Package Manager.

    (Tools > Nuget Packager Manager > Package Manager Console >  Install-Package AngularJs).

  3.  Code the default.aspx page.
Include AngularJs reference.

The Script
  1. <script type="text/javascript" src="Scripts/Angular.min.js"></script>  
Create the LocalStorage Service Module to read and write the data.
  1.             //Create the AngularJS module named StorageService
  2.             //Create getLocalStorage service to access UpdateEmployees and getEmployees method  
  3.             var storageService = angular.module('storageService', []);  
  4.             storageService.factory('getLocalStorage'function () {                  
  5.                 var employeeList = {};  
  6.                 return {  
  7.                     list: employeeList,  
  8.                     updateEmployees: function (EmployeesArr) {  
  9.                         if (window.localStorage && EmployeesArr) {  
  10.                             //Local Storage to add Data  
  11.                             localStorage.setItem("employees", angular.toJson(EmployeesArr));  
  12.                         }  
  13.                         employeeList = EmployeesArr;  
  14.                          
  15.                     },  
  16.                     getEmployees: function () {  
  17.                         //Get data from Local Storage  
  18.                         employeeList = angular.fromJson(localStorage.getItem("employees"));                         
  19.                         return employeeList ? employeeList : [];  
  20.                     }  
  21.                 };  
  22.   
  23.             });  
Create an AngularJs Employee module and register with the storageService. Add the other functionalities to add, delete and count employees.
  1. // Create the AngularJS module Employees and Register the storageService with it  
  2. var app = angular.module('Employees', ['storageService']);    
  3.   
  4. // Create the Controller EmployeeController  
  5. app.controller('EmployeesController', ['$scope''getLocalStorage', function ($scope, getLocalStorage) {    
  6.     $scope.appTitle = "LocalStorage Demo";    
  7.     $scope.appHeadline = "AngularJS and HTML5";    
  8.   
  9.     //Read the Employee List from LocalStorage    
  10.     $scope.employees = getLocalStorage.getEmployees();    
  11.   
  12.     //Count the Employee List    
  13.     $scope.count = $scope.employees.length;    
  14.   
  15.   
  16.     //Add Employee - using AngularJS push to add Employee in the Employee Object    
  17.     //Call Update Employee to update the locally stored Employee List    
  18.     //Reset the AngularJS Employee scope    
  19.     //Update the Count    
  20.     $scope.addEmployee = function () {    
  21.         $scope.employees.push({ 'empno': $scope.empno, 'empname': $scope.empname, 'empsalary': $scope.empsalary});    
  22.         getLocalStorage.updateEmployees($scope.employees);    
  23.         $scope.empno = '';    
  24.         $scope.empname = '';    
  25.         $scope.empsalary = '';    
  26.         $scope.count = $scope.employees.length;    
  27.     };    
  28.         
  29.     //Delete Employee - Using AngularJS splice to remove the emp row from the Employee list    
  30.     //All the Update Employee to update the locally stored Employee List    
  31.     //Update the Count    
  32.     $scope.deleteEmployee = function (emp) {                       
  33.         $scope.employees.splice($scope.employees.indexOf(emp), 1);    
  34.         getLocalStorage.updateEmployees($scope.employees);    
  35.         $scope.count = $scope.employees.length;    
  36.     };    
  37. }]); 
The HTML
 
Add the ng-app to access AngularJs functionalities.
  1. <body ng-app="Employees">  
Add the Controller to access the Employee Service  functionalities.
  1. <div ng-controller="EmployeesController">  
Add the Form and bind input controls with the employee fields using ng-model. Add the required attribute to the fields that you want to be required.
  1. <form name="frm">    
  2.    <table>    
  3.        <tr>    
  4.            <td>Emp No   :    
  5.   
  6.            </td>    
  7.            <td>    
  8.                <input type="text" name="empno" ng-model="empno" required><br />    
  9.            </td>    
  10.        </tr>    
  11.        <tr>    
  12.            <td>Emp Name   :    
  13.   
  14.            </td>    
  15.            <td>    
  16.                <input type="text" name="empname" ng-model="empname" required>    
  17.            </td>    
  18.        </tr>    
  19.        <tr>    
  20.            <td>Emp Salary   :    
  21.   
  22.            </td>    
  23.            <td>    
  24.                <input type="text" name="empsalary" ng-model="empsalary">    
  25.            </td>    
  26.        </tr>    
  27.        <tr>    
  28.            <td colspan="2" align="right">    
  29.   
  30.                <button ng-click="addEmployee()" ng-disabled="frm.$invalid">Add Employee</button>    
  31.            </td>    
  32.   
  33.        </tr>    
  34.    </table>    
  35. lt;/form> 
Add the table to display the Employee List and Delete button:
  • Using ng-repeat in tr to loop all employees in the list.
  • Display employee fields using scope {{ }}.
  • Call deleteEmployee on button click and pass the employee object to delete. 
  1.  <table cellpadding="4" cellspacing="4" border="1" style="border-collapse: collapse; border: solid 1px #000">    
  2.     <tr>    
  3.         <td><b>Emp No</b></td>    
  4.         <td><b>Emp Name</b></td>    
  5.         <td><b>Emp Salary</b></td>    
  6.         <td><b>Action</b></td>    
  7.     </tr>    
  8.     <tr ng-repeat="employee in employees">    
  9.         <td>{{ employee.empno }}    
  10.         </td>    
  11.         <td>{{ employee.empname }}    
  12.         </td>    
  13.         <td>{{ employee.empsalary }}    
  14.         </td>    
  15.         <td>    
  16.             <button ng-click="deleteEmployee(employee)">Delete</button>    
  17.   
  18.         </td>    
  19.     </tr>    
  20.   
  21. </table>    
  22. <div>Total Employees : {{count}}</div>    
  23. </div>   
The full Code
  1. <!DOCTYPE html>  
  2.   
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6.     <!--[if lte IE 8]>  
  7.          document.write("NOT HTML5 Compatible!!");  
  8.     <![endif]-->  
  9.   
  10.     <script type="text/javascript" src="Scripts/Angular.min.js"></script>  
  11.     <script type="text/javascript">  
  12.         var isHtml5Compatible = document.createElement('canvas').getContext != undefined;  
  13.   
  14.         if (isHtml5Compatible) {  
  15.             initiateLocalStorage();  
  16.   
  17.         }  
  18.   
  19.         function initiateLocalStorage() {  
  20.             // Create the AngularJS app   
  21.             var app = angular.module('Employees', ['storageService']);  
  22.   
  23.             // Create the Controller  
  24.             app.controller('EmployeesController', ['$scope', 'getLocalStorage', function ($scope, getLocalStorage) {  
  25.                 $scope.appTitle = "LocalStorage Demo";  
  26.                 $scope.appHeadline = "AngularJS and HTML5";  
  27.   
  28.                 //Read the Employee List from LocalStorage  
  29.                 $scope.employees = getLocalStorage.getEmployees();  
  30.   
  31.                 //Count the Employee List  
  32.                 $scope.count = $scope.employees.length;  
  33.   
  34.   
  35.                 //Add Employee - using AngularJS push to add Employee in the Employee Object  
  36.                 //Call Update Employee to update the locally stored Employee List  
  37.                 //Reset the AngularJS Employee scope  
  38.                 //Update the Count  
  39.                 $scope.addEmployee = function () {  
  40.                     $scope.employees.push({ 'empno': $scope.empno, 'empname': $scope.empname, 'empsalary': $scope.empsalary });  
  41.                     getLocalStorage.updateEmployees($scope.employees);  
  42.                     $scope.empno = '';  
  43.                     $scope.empname = '';  
  44.                     $scope.empsalary = '';  
  45.                     $scope.count = $scope.employees.length;  
  46.                 };  
  47.   
  48.                 //Delete Employee - Using AngularJS splice to remove the emp row from the Employee list  
  49.                 //All the Update Employee to update the locally stored Employee List  
  50.                 //Update the Count  
  51.                 $scope.deleteEmployee = function (emp) {  
  52.                     $scope.employees.splice($scope.employees.indexOf(emp), 1);  
  53.                     getLocalStorage.updateEmployees($scope.employees);  
  54.                     $scope.count = $scope.employees.length;  
  55.                 };  
  56.             }]);  
  57.   
  58.             //Create the Storage Service Module  
  59.             //Create getLocalStorage service to access UpdateEmployees and getEmployees method  
  60.             var storageService = angular.module('storageService', []);  
  61.             storageService.factory('getLocalStorage', function () {  
  62.                 var employeeList = {};  
  63.                 return {  
  64.                     list: employeeList,  
  65.                     updateEmployees: function (EmployeesArr) {  
  66.                         if (window.localStorage && EmployeesArr) {  
  67.                             //Local Storage to add Data  
  68.                             localStorage.setItem("employees", angular.toJson(EmployeesArr));  
  69.                         }  
  70.                         employeeList = EmployeesArr;  
  71.   
  72.                     },  
  73.                     getEmployees: function () {  
  74.                         //Get data from Local Storage  
  75.                         employeeList = angular.fromJson(localStorage.getItem("employees"));  
  76.                         return employeeList ? employeeList : [];  
  77.                     }  
  78.                 };  
  79.   
  80.             });  
  81.         }  
  82.     </script>  
  83.   
  84. </head>  
  85. <body ng-app="Employees">  
  86.   
  87.     <div ng-controller="EmployeesController">  
  88.   
  89.         <h1 class="app-title">{{ appTitle }}</h1>  
  90.         <h1 class="app-headline">{{ appHeadline }}</h1>  
  91.   
  92.         <form name="frm">  
  93.             <table>  
  94.                 <tr>  
  95.                     <td>Emp No   :  
  96.   
  97.                     </td>  
  98.                     <td>  
  99.                         <input type="text" name="empno" ng-model="empno" required><br />  
  100.                     </td>  
  101.                 </tr>  
  102.                 <tr>  
  103.                     <td>Emp Name   :  
  104.   
  105.                     </td>  
  106.                     <td>  
  107.                         <input type="text" name="empname" ng-model="empname" required>  
  108.                     </td>  
  109.                 </tr>  
  110.                 <tr>  
  111.                     <td>Emp Salary   :  
  112.   
  113.                     </td>  
  114.                     <td>  
  115.                         <input type="text" name="empsalary" ng-model="empsalary">  
  116.                     </td>  
  117.                 </tr>  
  118.                 <tr>  
  119.                     <td colspan="2" align="right">  
  120.   
  121.                         <button ng-click="addEmployee()" ng-disabled="frm.$invalid">Add Employee</button>  
  122.                     </td>  
  123.   
  124.                 </tr>  
  125.             </table>  
  126.         </form>  
  127.         <table cellpadding="4" cellspacing="4" border="1" style="border-collapse: collapse; border: solid 1px #000">  
  128.             <tr>  
  129.                 <td><b>Emp No</b></td>  
  130.                 <td><b>Emp Name</b></td>  
  131.                 <td><b>Emp Salary</b></td>  
  132.                 <td><b>Action</b></td>  
  133.             </tr>  
  134.             <tr ng-repeat="employee in employees">  
  135.                 <td>{{ employee.empno }}  
  136.                 </td>  
  137.                 <td>{{ employee.empname }}  
  138.                 </td>  
  139.                 <td>{{ employee.empsalary }}  
  140.                 </td>  
  141.                 <td>  
  142.                     <button ng-click="deleteEmployee(employee)">Delete</button>  
  143.   
  144.                 </td>  
  145.             </tr>  
  146.   
  147.         </table>  
  148.         <div>Total Employees : {{count}}</div>  
  149.          </div>  
  150.   
  151. </body>  
  152. </html>  
Output
 
 

The data to be added will remain stored even after the browser is closed.