Skip to content Skip to sidebar Skip to footer

How To Add Local Storage In Angular?

I made a table using angular, everything works great for now. Now I would like to add local storage feature. I really tried to achieve this but I came to a point I don't now what t

Solution 1:

Have a look at this implementation I did for dealing with local storage. This is really simple and really does not need any third party library.

(function() {
    'use strict';
    angular.module('myApp')
        .service('LocalStorageService', [
            '$window', function($window) {
                var service = {
                    store: store,
                    retrieve: retrieve,
                    clear: clear,
                    clearAll: clearAll
                };

                return service;

                functionstore(key, value) {
                    $window.localStorage.setItem(key, angular.toJson(value, false));
                }

                functionretrieve(key) {
                    return$window.localStorage.getItem(key);
                    // return angular.fromJson($window.localStorage.getItem(key));// I'm not 100% sure, but I think I need to de-serialize the json that was stored
                }

                functionclear(key) {
                    $window.localStorage.removeItem(key);
                }


                functionclearAll() {
                    $window.localStorage.clear();
                }


            }
        ]);
})();

If you want to use it, you just need to inject it inside your controller, and begin to use it.

eg :

table.controller('TodoCtrl', function($scope, $http, LocalStorageService) {
    $scope.todos = LocalStorageService.retrieve('todos');
    if (!$scope.todos){    // if 'todos' was not previously stored, $scope.todos will be null$http.get('todos.json').then(function(res) {
            $scope.todos = res.data;
            LocalStorageService.store('todos', $scope.todos);
        });
    }

}

Post a Comment for "How To Add Local Storage In Angular?"