Store Data Locally using $localstorage in AngularJS

Hi all, This is my first time writing a blog. So please don’t mind small mistakes (if any).

Today we are going to discuss how we can store data locally using $localstorage in AngularJS.
For that you need to follow some pretty easy steps:

Step 1 : Add an HTML file and add following references and code to it,

  1. <script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>  
• Angular.min.js file

As shown below,

code
Step 2: Add javascript file and provide its reference in index.html.

Step 3: Add the following code to your javascript file,
  1. angular.module('app', ['ngStorage']).  
  2.         
  3.         controller('Ctrl', function ($scope, $localStorage, $http) {  
  4.             if ($localStorage.datastorage) {  
  5.                 $scope.Applicantdata = $localStorage.datastorage;  
  6.                 alert("Second Time Call");  
  7.             }  
  8.             else{  
  9.   
  10.             $http.get("http://www.w3schools.com/angular/customers.php").then(function (response) {  
  11.                 $scope.Applicantdata = response.data.records;  
  12.                 $localStorage.datastorage = response.data.records;  
  13.                 alert("First Time Call");  
  14.             });  
  15.             }  
  16.         });  
As you can see, when the code will run for the first time it will check the datastorage variable of $localstorage. If datastorage variable has some data then the if part will be executed and it will not hit the server for data. Otherwise else case will be executed and a request will be made to server for the data, also it will store the data in datastorage variable. Once the data is stored in the datastorage variable then there is no need for requesting the server.

Thank You for reading the article – Happy Coding.