3

How to Store angularJS Variable Data into local temp storage for further usage as like session in server side.

The AngularJS Source Code is

var pApp = angular.module('ProfileIndex', []);
pApp.controller('ProfileIndexCtrl', function($scope, $http, $cacheFactory) {
  $scope.data = "MVVM";
});

How to Store the MVVM value in the local storage? and how to retrieve the value from the local storage?

0

3 Answers 3

1

Simply use the web storage API

// set "data" to "MVVM"
$window.localStorage.setItem('data', 'MVVM');

// get "data"
$window.localStorage.getItem('data');
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of using web storage api, is better you use angular storage ngStorage.

There is different between using web storage and angular storage especially when you want to store object to your storage.

For web storage you need to serialize your object before saving your data into web storage then you need to unserialized to get the data.

eg:

store- localStorage.setItem('saveData', JSON.stringify(myObj));

get- JSON.parse(localStorage.getItem('saveData'));

for angular storage you can simply store you data in ngStorage.

eg:

store- $localStorage.obj = myObj;

example object:

var myObj = {'firstname': 'john', 'secondname': 'cena'}

for more information about ngStorage you can see this link ngStorage

Comments

0

Use a factory:

.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    remove: function(key) {
      $window.localStorage.removeItem(key);
    },
    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
      return JSON.parse($window.localStorage[key] || '{}');
    },
    clearAll: function() {
      $window.localStorage.clear();
    }
  }
}])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.