HTML5 local storage with Angular JS

In this tutorial I will use the HTML5 browser local storage along with Angular JS. This storage is very useful for making applications work in offline mode and quickly shift to online mode. This ensures that the application will work without fail even if the internet connectivity is not available.

Local storage API and the Angular JS

Local storage API is available with all modern HTML5 browsers ranging from mobile devices to desktops. And I found this simple and effective module for Angular JS which lets you use the local storage API inside Angular.

I found this module on Github which does the magic: https://github.com/grevory/angular-local-storage. There are few very simple functions available for local storage which you can find here: http://diveintohtml5.info/storage.html and the same is replicated here.

What we will do?

In this tutorial, I will have a variable inside my controller scope which will save the list of active orders. But the main logic is how this variable will get its data? If the data is available via local storage, then we will fetch the saved data. But, if that data is not available then we will make an ajax call and fetch the data. Save the data in local storage and also use the same to display.

Setting up the controllers

I have setup two controllers; one for the page where I will show the data which is localstorage/index and the second is for the Ajax call from where I will get the data if the local storage data is not available.

[NOTE: This tutorial is just for demo where I have just checked if we have data in local storage and made a decision. Ideally we would make a call to the server, check if there is new data and only then we would replace the local data.]
class Localstorage extends CI_Controller
{

  public function __construct()
  {
    parent::__construct();
  }

  public function index()
  {
    $this->carabiner->js('localstorage/angularls.js');
    $this->carabiner->js('localstorage/app_script.js');
    $data['header']['page_title'] = 'Learning CI Tutorial - Notification order listing'; // title for the page
    $data['content']['view_name'] = 'localstorage/index'; // name of the partial view to load
    $data['content']['view_data'] = array(); // data coming inside the view

    $this->load->view('main_page_view',$data);
  }

}
class Ajax extends CI_Controller
{

  public function __construct()
  {
    parent::__construct();
    is_ajax_req();
  }

  public function get_active_orders()
  {
    $this->load->model('orders_model', 'o');
    $data = $this->o->get_active_orders();
    echo json_encode($data);
  }

}

Apart from this I have a model through which I am getting the latest set of active orders. The Ajax controller is getting the data and printing out the JSON.

The Angular JS code

/*define the application*/
var localstorageApp = angular.module('localstorageApp', ['LocalStorageModule']);

localstorageApp.factory('sharedOrders', ['$http', '$rootScope', function($http, $rootScope) {
  var orders = [];
  return {
    getOrders: function() {
      return $http.get(base_url + 'ajax/get_active_orders').then(function(response) {
        orders = response.data;
        $rootScope.$broadcast('handleSharedOrders',orders);
        return orders;
      })
    }
  };
}]);

localstorageApp.controller('MainCtrl', ['$scope', '$rootScope', 'localStorageService', 'sharedOrders', function($scope, $rootScope, localStorageService, sharedOrders) {
  $scope.welcome = "Local storage with Angular JS example";
  $scope.orders = localStorageService.get('localOrders');
  $scope.source = "Local";
  if ($scope.orders == null) {
    console.log('http required');
    sharedOrders.getOrders().then(function(response) {
      $scope.orders = response;
      $rootScope.$broadcast('handleSharedOrders',response);
      localStorageService.add('localOrders',$scope.orders);
      $scope.source = "Online";
    })
  }
  else {
    console.log('On local storage. Nothing do be done.');
  }
}]);

In the first part I have the module definition and a factory method which is same as the notification tutorial where it is fetching the content from the Ajax controller.

Inside the MainCtrl controller I have the "localStorageService" which is the module connecting the browser local storage API within Angular.

First I have a get call to take the data from local storage into my scope variable. Then I have the if condition to check if the value is null and accordingly I am calling the http service to get the JSON data.

If you run this page, first time you will see that an http ajax call is made. Next time nothing of that sort is done. You can also close the browser and re open the page to find that we are still fetching the content from local storage and no http call is made. But if you clear your browser cache and then load the page, you will see the Ajax call made to the server.

You can view the demo here: http://demos.amitavroy.com/learningci/localstorage

comments powered by Disqus