0

I use ngStorage (https://github.com/gsklee/ngStorage) for storing some data in the localStorage of the browser.

I have this markup

<ul class="cards">
    <li ng-repeat="card in cards">
        <card></card>
    </li>
</ul>

With a "card" (as u can see) directive, that stores my template for each card.

In my Controller I have this method to push a card in the ng-repeat Array of cards:

 angular.controller('CustomerController', function($scope, $localStorage, $sessionStorage) {
      $scope.cards = [];
      $scope.addCardRed = function() {
          return $scope.cards.push(new Card("red"));
      };
(...)
});

That works so far. But I can't accomplish to store the cards in my ul. I tried some variations of:

 (...)
 $scope.$storage = $localStorage;
 $scope.cards = [];
 $localStorage.cards = [];
 $localStorage.cards = $scope.cards;

But either my cards won't displayed in the list anymore or the list won't be stored. What can I do to store my card elements in the list? What am I doing wrong?

djot
  • 2,952
  • 4
  • 19
  • 28
christophe
  • 692
  • 4
  • 14
  • 27
  • What error do you get in your console when your cards don't appear? – jbarnett Oct 13 '13 at 18:34
  • I get an error ("no method push") when I don't use the line $localStorage.cards = []; But this is obvious. Otherwise the cards will be displayed as usual, but not stored. I don't know how to assign the cards to the storage properly. – christophe Oct 13 '13 at 18:42

1 Answers1

2

I think, your Card is not a Simple JavaScript Object. therefore you may want to use something like this:

angular.module('storage',[]).factory('cardStorage',function(){
var key = 'cards';
var store =  localStorage;

// Card has to be JSON serializable
function assign(value){store[key]=JSON.stringify(value)};

// return Card instances
function fetch(){return (JSON.parse(store[key])||[]).map(
  function(card){return new Card(card);
})};

return {
  bind:function(scope,attribute,defaults){
    // read from storage - in case no data in scope
    if(!(attribute in scope)){
      scope[attribute]=fetch();
    }
    // observe changes in cars and persist them
    scope.$watch(attribute,function(next,prev){
      assign(next);
    },true);
  }
}

});

and in your Controller

function(scope,cardStorage){
   cardStorage.bind('cards');
}

or you can use : https://github.com/agrublev/angularLocalStorage

g00fy
  • 4,717
  • 1
  • 30
  • 46