Reputation: 25
I am new to Ionic and AngularJS. I am trying to store an array of objects to local storage. The code below works fine if I only store one object (I am able to retrieve the data). The problem arises when I try to store and access data from an array of objects (prints blank).
Here is my 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'] || '[]');
};
I validate data stored in local storage using Storage Inspector in Mozilla. This is the result:
Can anyone Help me?
Upvotes: 2
Views: 4145
Reputation: 130
You can use this code to store an array object to local storage:
localStorage.setItem('alarms', JSON.stringify($scope.alarms));
to retrieve the stored values use this:
$scope.alarms = (localStorage.getItem('alarms')!==null) ? JSON.parse(localStorage.getItem('alarms')) : [];
Upvotes: 1
Reputation: 5167
The previously set alarms must first retrieved and stored in a variable. Then push the new alarm in this variable and put them back in storage. With this way you can store an array of objects in the storage. If you dont retrieve the currently saved alarms then you will not be able to save more than one alarm in the storage because every new one will overwrite the previous
$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'));
};
}
Upvotes: 0
Reputation: 2105
localStorage.getItem('itemName') it's what you are looking for, you need to modify your getalarms function:
$scope.getalarms = function (){
$scope.alarms = JSON.parse(localStorage.getItem('alarms'));
};
Upvotes: 0