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.