Firstly, include the ngStorage source in your index.html.
An example injecting ngStorage
src would be:
<head>
<title>Angular JS ngStorage</title>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>
</head>
ngStorage
gives you 2 storage namely: $localStorage
and $sessionStorage
. You need to require ngStorage and Inject the services.
Suppose if ng-app="myApp"
, then you would be injecting ngStorage
as following:
var app = angular.module('myApp', ['ngStorage']);
app.controller('controllerOne', function($localStorage,$sessionStorage) {
// an object to share
var sampleObject = {
name: 'angularjs',
value: 1
};
$localStorage.valueToShare = sampleObject;
$sessionStorage.valueToShare = sampleObject;
})
.controller('controllerTwo', function($localStorage,$sessionStorage) {
console.log('localStorage: '+ $localStorage +'sessionStorage: '+$sessionStorage);
})
$localStorage
and $sessionStorage
is globally accessible through any controllers as long as you inject those services in the controllers.
You can also use the localStorage
and sessionStorage
of HTML5
. However, using HTML5
localStorage
would require you to serialize and deserialize your objects before using or saving them.
For example:
var myObj = {
firstname: "Nic",
lastname: "Raboy",
website: "https://www.google.com"
}
//if you wanted to save into localStorage, serialize it
window.localStorage.set("saved", JSON.stringify(myObj));
//unserialize to get object
var myObj = JSON.parse(window.localStorage.get("saved"));