In this article I will explain with an example, how to save and retrieve data from HTML5 LocalStorage and SessionStorage objects using AngularJS.
 
 
Save and retrieve data from LocalStorage and SessionStorage using AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
Along with the AngularJS JavaScript file, ngStorage.min.js file also needs to be inherited in order to perform operations on HTML5 LocalStorage and SessionStorage objects.
The ng-controller uses ngStorage module and $localStorage and $sessionStorage services in order to access the HTML5 LocalStorage and SessionStorage objects.
Note: If you want to learn more about these directives, please refer my article Introduction to AngularJS.
 
The AngularJS app HTML DIV consists of two HTML Buttons specified with ng-click-html directive. These Buttons are used to save and retrieve data from HTML5 LocalStorage and SessionStorage objects.
Note: If you want to learn more about ng-click directive, please refer my article ng-click directive example.
 
Saving data from HTML5 LocalStorage and SessionStorage
When the Save Button is clicked, the Save function of the controller gets called which saves the string message to the HTML5 LocalStorage and SessionStorage objects.
 
Retrieving data from HTML5 LocalStorage and SessionStorage
When the Get Button is clicked, the Get function of the controller gets called which gets the string message from the HTML5 LocalStorage and SessionStorage objects and displays it using JavaScript Alert message box.
Note: If you want to learn more on displaying JavaScript alert with AngularJS, please refer my article AngularJS: Display (Show) JavaScript Alert box.
 
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ["ngStorage"])
        app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
            $scope.Save = function () {
                $localStorage.LocalMessage = "LocalStorage: My name is Mudassar Khan.";
                $sessionStorage.SessionMessage = "SessionStorage: My name is Mudassar Khan.";
            }
            $scope.Get = function () {
                $window.alert($localStorage.LocalMessage + "\n" + $sessionStorage.SessionMessage);
            }
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <input type="button" value="Save" ng-click="Save()" />
        <input type="button" value="Get" ng-click="Get()" />
    </div>
</body>
</html>
 
 
Screenshot
AngularJS: Save and retrieve data from LocalStorage and SessionStorage
 
 
Demo
 
 
Downloads