Skip to content

Instantly share code, notes, and snippets.

@cerebrl
Created June 28, 2013 17:39
Show Gist options
  • Save cerebrl/5886544 to your computer and use it in GitHub Desktop.
Save cerebrl/5886544 to your computer and use it in GitHub Desktop.
localStorage with AngularJS

AngularJS localStorage

This was nabbed from DailyJS

There are examples of apps that use localStorage on the AngularJS blog. One that I downloaded and picked apart was FoodMe by Igor Minar. In FoodMe, Igor creates a localStorage service which basically just wraps window.localStorage so it can be loaded with dependency injection. The $scope is then watched, and a string version of a given record is dumped into localStorage using JSON.stringify:

foodMeApp.factory('customer', function($rootScope, localStorage) {
	var LOCAL_STORAGE_ID = 'fmCustomer';
	var customerString = localStorage[LOCAL_STORAGE_ID];

	var customer = customerString ? JSON.parse(customerString) : {
		name: undefined,
		address: undefined
	};

	$rootScope.$watch(function() { return customer; }, function() {
		localStorage[LOCAL_STORAGE_ID] = JSON.stringify(customer);
	}, true);

	return customer;
});

The record is loaded from localStorage, and serialised using JSON.parse and JSON.stringify. Notice that Igor has used the object-style API: localStorage.setItem(key, value) and localStorage[key] = value are equivalent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment