我使用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;
但是我的卡片将不再显示在列表中,或者列表将不再存储。如何操作才能将卡片元素存储在列表中?我做错了什么?
我认为,你的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