0

我使用 ngStorage ( https://github.com/gsklee/ngStorage ) 在浏览器的 localStorage 中存储一些数据。

我有这个标记

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

使用“卡片”(如您所见)指令,为每张卡片存储我的模板。

在我的控制器中,我有这种方法可以将卡片推送到 ng-repeat 卡片数组中:

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

到目前为止有效。但是我无法将卡片存储在我的 ul 中。我尝试了一些变体:

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

但是要么我的卡片不再显示在列表中,要么列表不会被存储。我可以做些什么来将我的卡片元素存储在列表中?我究竟做错了什么?

4

1 回答 1

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

于 2013-10-14T00:50:46.420 回答