4

I am having single page application with user authentication and there is no problem sharing session information there.

However I have part of site where are static pages where I would like just to include session information (logged in user, or login form). How I can share session information between two apps?

||||||
12

I would recommend creating a service that wraps localStorage or other apis to store persistent data. Here is an example using a localStorage implementation.

This implementation is synchronous but if I would use websql like or even server db then I would refactor it to use promises to return the storage object.

Controller

var demo = angular.module('demo', [ 'appStorage' ]);

demo.controller('AppStorageController', [ '$scope', 'appStorage',
    function($scope, appStorage) {
      appStorage('MyAppStorage', 'myAppStorage', $scope);
    } ]);

HTML

<div ng-controller="AppStorageController">
  <p>Local Storage: {{myAppStorage}}</p>
  <p>
    Username: <input type="text" ng-model="myAppStorage.username"></input>
  </p>
  <p>
    Remember me: <input type="checkbox"
      ng-model="myAppStorage.rememberMe"></input>
  </p>
</div>

JS

angular.module('appStorage', []).factory('appStorage',
    [ '$window', function($window) {
      var appStorages = {};
      var api = undefined;

      if ($window.localStorage) {
        api = {
          set : function(name, value) {
            $window.localStorage.setItem(name, JSON.stringify(value));
          },
          get : function(name) {
            var str = $window.localStorage.getItem(name);
            var val = {};
            try {
              val = str ? JSON.parse(str) : {};
            }
            catch (e) {
              console.log('Parse error for localStorage ' + name);
            }
            return val;
          },
          clear : function() {
            $window.localStorage.clear();
          }
        };
      }
      // possibly support other

      if (!api) {
        throw new Error('Could not find suitable storage');
      }

      return function(appName, property, scope) {
        if (appName === undefined) {
          throw new Error('appName is required');
        }

        var appStorage = appStorages[appName];

        var update = function() {
          api.set(appName, appStorage);
        };

        var clear = function() {
          api.clear(appName);
        };

        if (!appStorage) {
          appStorage = api.get(appName);
          appStorages[appName] = appStorage;
          update();
        }

        var bind = function(property, scope) {
          scope[property] = appStorage;
          scope.$watch(property, function() {
            update();
          }, true);
        };

        if (property !== undefined && scope !== undefined) {
          bind(property, scope);
        }

        return {
          get : function(name) {
            return appStorage[name];
          },
          set : function(name, value) {
            appStorage[name] = value;
            update();
          },
          clear : clear
        };
      };
    } ]);
||||||
  • How could I clean a property or a storage app using this appStorage service. For example, if I created a FooStorage app and placed a bar property in it under $scope using appStorage('FooStorage', 'bar', $scope); then what could I do to clean just the bar property and what if I needed to clean the whole FooStorage? – skip Sep 12 '14 at 23:36
  • 1
    @skip I would add a removeApp method to the api that will call localStorage.removeItem by the name of the app in this case FooStorage. If you want to remove a property then add a remove method that will delete the property in the map then resave the value to localStorage. – Liviu T. Sep 13 '14 at 20:21
  • If I have var fooStore = appStorage('FooStorage', 'bar', $scope);, should calling fooStore.clear(); not clear all the data stored in the fooStore? I get the the stored data even after I reload the page after calling the fooStore.clear();. How could I clear all the data from fooStore? Thanks. – skip Sep 14 '14 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.