Amitav Roy

Blog on web and travel

HTML5 local storage with Angular JS

Posted on 6 Jul 2013 by Amitav Roy

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: There are few very simple functions available for local storage which you can find here: 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 set up 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 the 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.]

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

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, the 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 reopen 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.