Skip to main content
How to Use HTML5 Local Storage Using AngularJS

How to Use HTML5 Local Storage Using AngularJS

This is a simple Angularjs tutorial to read and write data into HTML5 local storage. The Angularjs framework already has module angular-local-storage that helps to access the browser’s local storage.

I will not use a third-party angular module for local storage. The HTML5 Local storage data is available in the browser to all windows with the same.

I will create simple ng-app to store data into localstorage and read saved data from that. It’s a very simple and easy-to-use HTML5 local storage using angular 1.4. HTML5 Local storage also provides functionality to send events between browser windows.

What’s HTML5 LocalStorage

The HTML5 local storage is similar to cookies as you have used any programming language. The main difference is that cookies are set by the server to the browser and localstorage is set via JavaScript into the browser.

The cookie length is the max 4KB whereas an HTML5 localstorage does not have a limit.

Benefit’s Of HTML5 LocalStorage

The main benefit of HTML5 local storage is that only the same domain pages can get local storage values no other domain can access local storage values. There are two variants of HTML5 local storage available,

  • sessionStorage: The Session storage data is available only to the same browser window
  • localStorage: The data is available in browser windows with the same origin (domain)

Checkout Other Localstorage tutorials,

How to Set Value In Local Storage Using AngularJS

You can use setItem(key, val) method to store the data in local storage. The first param is the key and the second is the value of data. You can see a simple example below,

var data = {
'name' : adam,
'age' : 34
}

localStorage.setItem("sample_data", JSON.stringify($scope.data));
localStorage.setItem("env", 'dev');

How to Get Value from HTML5 Local Storage Using AngularJS

You can use getItem(key) method to get the stored data of HTML5 local storage. The param 'key' is the key name of the data. You can see a simple example below,

if(localStorage.getItem('sample_data') != null){
   $scope.data = JSON.parse(localStorage.getItem('sample_data'));
   $scope.env = localStorage.getItem("env");
}

How to Remove Data from localStorage Using AngularJS

You can use removeItem(key) method to remove data from HTML5 local storage. You can see a simple example below,

localStorage.removeItem('sample_data');
localStorage.removeItem('env');

How to Remove All Data from LocalStorage Using AngularJS

The clear() method is used to remove all saved data from localStorage.You can see a simple example below,

//remove the sample_data and env saved data from localStorage
localStorage.clear();

How to Set Value In sessionStorage Using AngularJS

You can use setItem(key, val) method to store the data in session storage. The first param is the key and the second is the value of data. You can see a simple example below,

var data = {
'name' : adam,
'age' : 34
}

sessionStorage.setItem("sample_data", JSON.stringify($scope.data));
sessionStorage.setItem("env", 'dev');

How to Get Value from HTML5 sessionStorage Using AngularJS

The getItem(key) method to get the stored data from HTML5 sessionStorage.The param 'key' is the key name of the data. You can see a simple example below,

if(sessionStorage.getItem('sample_data') != null){
   $scope.data = JSON.parse(sessionStorage.getItem('sample_data'));
   $scope.env = sessionStorage.getItem("env");
}

How to Remove Data from SessionStorage Using AngularJS

Now, I can use removeItem(key) method to remove data from sessionStorage.You can see a simple example below,

sessionStorage.removeItem('sample_data');
sessionStorage.removeItem('env');

How to Remove All Data from SessionStorage Using AngularJS

The clear() method is used to remove all saved data from sessionStorage. You can see a simple example below,

//remove the sample_data and env saved data from sessionStorage
sessionStorage.clear();

You can also get the current locastorage object length, You can get locastorage or sessionStorage using the below way,

var length = sessionStorage.length;
var length = localStorage.length;

How to get all localStorage saved data

Sometimes, we don’t have information about which keys are using what values contained in localStorage. This also provides the functionality to find the display stored key-value pair.

for(var i=0; i < localStorage.length; i++){

    var keyName = localStorage.key(i);

    console.log( keyName + " === " +sessionStorage.getItem(keyName));
}

The sessionStorage and localStorage are worked on all modern browsers which are supporting HTML5, like Chrome, Mozila, Safari and Opera etc.

LocalStorage Using AngularJs Factory

We can leverage an angular js factory to encapsulate and provide reusable functionality for working with HTML5 Local Storage. A factory allows you to create a service that can be injected into different parts of your application.

Step 1: Create a folder ‘angularjs-localstorage-sample’ and created index.html.

Added angular js file into the head section of index.html file. Create an Angular module and define a factory within it.

<script src="path/to/angular.min.js"></script>
<script>
  var app = angular.module('myApp', []);
  
  app.factory('localStorageService', function() {
    // Factory implementation goes here
  });
</script>

Step 2: Let’s define the local storage functions into a factory module, that ll interact with the Local Storage API.

<script>
  app.factory('localStorageService', function() {
    var service = {};

    service.setItem = function(key, value) {
      localStorage.setItem(key, value);
    };

    service.getItem = function(key) {
      return localStorage.getItem(key);
    };

    service.removeItem = function(key) {
      localStorage.removeItem(key);
    };

    return service;
  });
</script>

Step 3: You can now inject the localStorageService factory into your controller and use its functions to work with Local Storage.

<script>
  app.controller('EmpController', function($scope, localStorageService) {
    $scope.setValue = function(key, value) {
      localStorageService.setItem(key, value);
    };

    $scope.getValue = function(key) {
      return localStorageService.getItem(key);
    };

    $scope.removeValue = function(key) {
      localStorageService.removeItem(key);
    };
  });
</script>

Step 4: Now interact with local storage using the functions defined in the controller.

<div ng-app="myApp" ng-controller="EmpController">
    <input type="text" ng-model="data" placeholder="Enter value">
    <button ng-click="setValue('emp', data)">Save</button>
    <button ng-click="data = getValue('emp')">Retrieve</button>
    <button ng-click="removeValue('emp')">Clear</button>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *