AngularJS LocalStorage Factory

(function () { 'use strict';

angular
    .module('tt', [])
    .factory('ttLS', ttLocalStorage);

ttLocalStorage.$inject = ['$window'];

function ttLocalStorage($window)
{
    var factory =
    {
        //set: setLocalStorage,
        //get: getLocalStorage,
        //setObject: setObjectLocalStorage,
        //getObject: getObjectLocalStorage,
        set: setObjectLocalStorage,
        get: getObjectLocalStorage,
        remove: removeLocalStorage,
        clear: clearLocalStorage
    };

    return factory;

    // implementation below ===============================================

    function setLocalStorage(key, value)
    {
        $window.localStorage[key] = value;
    }

    function getLocalStorage(key, defaultValue)
    {
        return $window.localStorage[key] || defaultValue || false;
    }

    function setObjectLocalStorage(key, objectValue)
    {
        $window.localStorage[key] = angular.toJson(objectValue);
    }

    function getObjectLocalStorage(key, defaultObjectValue)
    {
        if ($window.localStorage[key] != undefined)
        {
            return angular.fromJson($window.localStorage[key]);
        }
        else
        {
            return defaultObjectValue || false;
        }
    }

    function removeLocalStorage(key)
    {
        $window.localStorage.removeItem(key);
    }

    function clearLocalStorage()
    {
        $window.localStorage.clear();
    }
}

})();

////////////////////////////////////////////////////////////////////////////// // Usage //////////////////////////////////////////////////////////////////////////////

//Inject ttLS to controller or other service/factor

ttLS.set("asdf", { a: 'a', b: 'b' }); $log.debug(ttLS.get("asdf", {}));

ttLS.set("one", 1); $log.debug(ttLS.get("one", 1));

ttLS.set("two", "twotwo"); $log.debug(ttLS.get("two", "twotwo"));

AUTHOR

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?