0

我使用ngStorage(https://github.com/gsklee/ngStorage)將一些數據存儲在瀏覽器的localStorage中。在AngularJS中使用指令的LocalStorage

我有這個標記

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

着有「牌」(就像你看到的)指令,存儲我的模板每張卡。

在我的控制器我有這樣的方法在卡的NG-重複陣列推卡:

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; 

但是我的卡片不會再顯示在列表中,或者列表將不會被存儲。我能做些什麼來將我的卡片元素存儲在列表中?我究竟做錯了什麼?

+0

你在控制檯中看到什麼錯誤時,你的卡不要沒有出現? – jbarnett

+0

當我不使用$ localStorage.cards = []時,出現錯誤(「no method push」);但這很明顯。否則,卡片將照常顯示,但不會存儲。我不知道如何正確地將卡分配給存儲。 – christophe

回答

2

我認爲,您的Card不是一個簡單的JavaScript對象。因此,你可能希望使用這樣的事:

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); 
    } 
} 

}); 

,並在控制器

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

,或者您可以使用: https://github.com/agrublev/angularLocalStorage