Lunny
Lunny

Reputation: 852

Angular ngStorage Custom Objects

I am using ngStorage to store data. I made a custom objects called game and stored it. Its stored as a game but when i refresh the browser it comes back as an Object.

var games= $localStorage.games || {};

this.addGame = function(){
    var newGame = new game("Game "+games.length);
    $localStorage.games = newGame;
  }

var game = function(title){
var title=title;
var player1;
var player2;
this.getTitle = function(){
  return title;
}
this.setTitle = function(title){
  this.title = title;
}
this.getPlayer1 = function(){
  return player1;
}
this.setPlayer1 = function(player1){
  this.player1 = player1;
}
this.getPlayer2 = function(){
  return player2;
}
this.setPlayer1 = function(player1){
  this.player2 = player2;
}
}

When a new game is added it's stored as a game in LocalStorage but when I refresh the bowser and tried to fetch games. It returns as an array of Objects not games.

Upvotes: 0

Views: 559

Answers (1)

S.Galarneau
S.Galarneau

Reputation: 2234

You cannot store objects in localStorage. The hack is that you can store string and parse/unparse them like this.

var game = {
  name: 'Super Metroid',
  text: 'This is an awesome game!!!'
};

window.localStorage['game'] = JSON.stringify(game);

var superMetroid = JSON.parse(window.localStorage['game'] || '{}');

Upvotes: 1

Related Questions