我是Ionic和AngularJS的新手。我试图将一组对象存储到本地存储。如果我只存储一个对象(我能够检索数据),下面的代码工作正常。当我尝试存储和访问对象数组中的数据(打印空白)时出现问题。
这是我的index.html
<ul class="list">
<li class="item" ng-repeat="alarm in alarms">
{{alarm.hour}}: {{alarm.min}} {{alarm.pos}}
<span class="item-toggle">
<label class="toggle toggle-balanced">
<input type="checkbox" ng-model="alarm.on" ng-click="completeTask($index)">
<div class="track">
<div class="handle"></div>
</div>
</label>
</span>
</li>
</ul>
</ion-content>
controller.js
$scope.createalarm = function (alarm) {
$scope.alarms.push({
hour : alarm.hour , min : alarm.min , pos : alarm.pos , on : true
});
window.localStorage['alarms'] = JSON.stringify($scope.alarms);
$scope.setalarm.hide();
};
$scope.getalarms = function (){
$scope.alarms = JSON.parse(window.localStorage['alarms'] || '[]');
};
我使用Mozilla中的Storage Inspector验证存储在本地存储中的数据。这是结果:
任何人都可以帮助我吗?
答案 0 :(得分:1)
您可以使用此代码将数组对象存储到本地存储:
localStorage.setItem('alarms', JSON.stringify($scope.alarms));
检索存储的值使用此:
$scope.alarms = (localStorage.getItem('alarms')!==null) ? JSON.parse(localStorage.getItem('alarms')) : [];
答案 1 :(得分:0)
localStorage.getItem(&#39; itemName&#39;)它是您要找的,您需要修改您的getalarms功能:
$scope.getalarms = function (){
$scope.alarms = JSON.parse(localStorage.getItem('alarms'));
};
答案 2 :(得分:0)
必须首先检索先前设置的警报并将其存储在变量中。然后在此变量中按下新警报并将其重新存储。通过这种方式,您可以在存储中存储一组对象。如果您没有检索当前保存的警报,那么您将无法在存储中保存多个警报,因为每个警报都会覆盖以前的警报
$scope.createalarm = function (alarm) {
//retrive all alarms that are currently in our localStorage
//if we dont do that every new alarm will overwrite the old one
$scope.alarms = JSON.parse(window.localStorage.getItem('alarms')) || [];
//push the new created alarm
$scope.alarms.push({
hour : alarm.hour , min : alarm.min , pos : alarm.pos , on : true
});
//save the newly created alarm back in the storage
window.localStorage.setItem('alarms', JSON.stringify($scope.alarms));
$scope.setalarm.hide();
$scope.getalarms = function (){
$scope.alarms = JSON.parse(window.localStorage.getItem('alarms'));
};
}