How to use LocalStorage in Angular JS

How to use LocalStorage in Angular JS

The localStorage is similar to sessionStorage, except that data is stored in localStorage but no expiration time, while data stored in sessionStroage gets clreared when the browsing session ends(i.e when the browser is closed).

The localStorage is not clear if we close the tab, close the browser. The data is stored only in that particular browser. if you are set data in chrome, then open to firebox the data is not available in firebox. But the data is availble on same browser(Chrome). 

The LocalStorage Exmple : 

<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', ['$scope', '$localStorage', '$sessionStorage', '$window',function ($scope, $localStorage, $sessionStorage, $window) {
            $scope.Save = function () {
                $localStorage.LocalMessage = $scope.myname;
            }
            $scope.Get = function () {
                $window.alert($localStorage.LocalMessage);
            }
        }]);
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
<input type="text" name="myname" ng-model="myname">
        <input type="button" value="Save" ng-click="Save()" />
        <input type="button" value="Get" ng-click="Get()" />
    </div>
</body>
</html>
 
If you want to close the loclstorage, after bootstraping your module call run and setup an $interval that clear the local storage after 20 minutes. 
 
app.run(function($interval){
  $interval( function(){
    delete localStorage[key];
    // delete all the required localStorage variables by specifying their keys
  }, 1000*60*20);
});

0 Comments

Leave a Replay

Make sure you enter the(*)required information where indicate.HTML code is not allowed

>