How To Use LocalStorage in AngularJS

February 28, 2017

How To Use LocalStorage in AngularJS

So when I started the Fair Offer Project to help people fairly compare their job offers, I decided to start by saving data locally.

Thus, I wouldn’t have to worry about adding complexity with a database backend.

Angular JS shield logo

This way I could focus on only the front-end tooling but still save job offer information.

Step 1 – Find a LocalStorage plugin to use

The first step was to find an Angular library that would let me hook into local storage. I eventually found angular-local-storage.

I’ve never used it but it had 2000+ stars on GitHub and code commits within the last several months. Hence, I thought it looked like it was being well-maintained.

So I decided it was a reliable library to use.

Step 2 – Configure bower.json and install

The next step was to add the file locally via bower.

bower.json

So I added the file below in bower.json.

"lodash": "~4.5.1",
"angular-local-storage": "~0.2.5"

app.js

I also needed to add a require statement to incorporate the dependency properly.

require('bower/angular-local-storage/dist/angular-local-storage');

I also needed to add a reference to LocalStorageModule to the list of angular dependencies.

module.exports = angular.module('fairOfferApp', [
         'ui.router',
         'LocalStorageModule',

Step 3 – Make the Angular controller aware of the dependency

Finally, to polish off the install, I needed to inject the dependency into the Angular controller.

angular.module('fairOfferApp.fair_offer')
.controller('fairOfferCtrl', [ '$scope', 'localStorageService', function ($scope, localStorageService) { ... }

Step 4 – Add a function to save to LocalStorage

Now, I could add some code to the Angular controller to enable a saveLocal function.

This function allowed me to save data to local storage in the browser.

isSupported) {
  console.log('no');
}
$scope.saveLocal = function() {
  localStorageService.set("factors", $scope.factors);
}

Step 5 – Get the saveLocal function working

The last step was to add it to the HTML template view.

<tr>
  <td colspan="2"><button ng-click="saveLocal()">Save Local</button></td>
</tr>

Summary

Enabling saving data to local storage in the browser was a matter of finding a well-maintained Angular library. Then I just had to get it working with the front end tooling with webpack.


Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.