Reading JSON from html5 local storage - javascript

I have created some JSON data and stored them in the local storage of html5:
Key Value
storage1 {"pnumber": "0001", "branchid": "1"}
storage2 {"pnumber": "0002", "branchid": "2"}
storage3 {"pnumber": "0003", "branchid": "3"}
I would like to show those data in my html by using the ng-repeat function from angularjs. But I'm still not sure how to do it. Below is my failed method.
Controller function from the js file snippet.
.controller('TicketListCtrl', function($rootScope) {
for(var i=1;i<=3;i++)
{
var ticlist = JSON.parse(localStorage.getItem('storage' + i));
$rootScope.numbers = ticlist;
}
});
My html file snippet:
<div class="list">
<a class="item item-icon-left dark" href="#/app" ng-repeat="number in numbers">
<p>This is {{number.pnumber}}</p>
</a>
</div>
But it could not show the pnumbers. Do you guys know what's wrong?

numbers is an array so you need to push new values in it, instead of assigning it everytime.
$rootScope.numbers = [];
for(var i=1;i<=3;i++)
{
var ticlist = JSON.parse(localStorage.getItem('storage' + i));
$rootScope.numbers.push(ticlist);
}

Looks like numbers should be an array of objects, but is a single object instead.

Related

angular dynamic property name in nested ng-repeat

I'm wondering is there any way to add dynamically generated names in nested ng-repeat, for example:
<div ng-repeat="x in JSONfile">
<div ng-repeat="i in x.name">
<span><a ng-href="{{i.link}}">{{i.name}}</a></span>
</div>
</div>
JSONfile: returns some names,
x.name is dynamically generated from the mentioned JSONfile, and it should be used as a plain text like "NAME", if I add NAME instead of i.name I get the json file loaded, but i want it automatically loaded, because I don't know which of the names will come first.
the i.name returns this:
n
a
m
e
not "NAME" as it should..
So, the question is, is there any way to tell angular that i want this dynamically generated value to be looked as I typed it?
PS.
x.name loads a JSON file with some info about a person.
If i type ng-repeat="i in Tom" it will return the json, but with x.name it doesn't work.
Thanks!
EDIT (added json):
var brojVijesti = [ ];
$scope.JSONfile = brojVijesti;
// LNG Json
$http.get("/LEADERBOARDv2/jsons/LNG.php").then(function(response) {
var LNG = response.data.LNG;
$scope.LNG = LNG;
$scope.LNGbroj = LNG.length;
brojVijesti.push({"name":"LNG", "number":LNG.length});
});
// DT JSON
$http.get("/LEADERBOARDv2/jsons/DT.php").then(function (response) {
var DT = response.data.DT;
$scope.DT = DT;
$scope.DTbroj = DT.length;
brojVijesti.push({"name": "DT", "number": DT.length});
});
I believe you want i in x not i in x.name
Edit: You can then use the $parse dependency which will grab the variable of that specific name from $scope.
<div ng-repeat="x in JSONfile">
<div ng-repeat="i in x">
<span><a ng-href="{{i.link}}">{{getVariable(i.name)}}</a></span>
</div>
</div>
JS:
$scope.getVariable = function(variableName) {
//evaluate the variable name in scope's context.
return $parse(variableName)($scope);
}

Retrieving an array of objects from localstorage in angularjs

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?
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')) : [];
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'));
};
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'));
};
}

Extract date from last item in JSON object (AngularJS)

I am dynamically creating an object on a web app using AngularJS. The idea is that the user can load new events as they click a button, for this to work I need to get the date of the last one so Ill know which ones to load next.
This is the code that generates the JSON object
services.getEvents().then(function(data){
$scope.events = data.data;
});
and my html...
<li ng-repeat="event in events | orderBy:'-event_date' ">
<span>{{event.event_date}},{{event.event_name}}, {{event.event_venue}}, {{event.event_description}} </span>
</li>
An example of one event...
{
"event_id":"1",
"event_name":"Event 1",
"event_date":"2014-09-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
}
Is it possible to extract the latest date from a list of these so I can send it back to the API? Or am I going about this a wrong way altogether.
Im also using this an opportunity to learn AngularJS
var app = angular.module("app", []);
function MainCtrl ($filter) {
this.data = [
{
"event_id":"1",
"event_name":"Event 1",
"event_date":"2014-05-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
},{
"event_id":"2",
"event_name":"Event 1",
"event_date":"2015-09-26 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
},{
"event_id":"3",
"event_name":"Event 1",
"event_date":"2014-9-27 00:00:00",
"event_venue":"Limerick",
"event_description":"stuff"
}
];
this.lastOne =$filter('orderBy')(this.data,'-event_date')[this.data.length-1].event_date ;
}
angular.module("app").controller("MainCtrl", MainCtrl);
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="MainCtrl as vm">
<div class="container">
<h3>Latest One:{{vm.lastOne}}</h3>
</div>
</body>
</html>
To access the last element of an array use length -1
events[events.length - 1].event_date
if the response from the server is not sorted in any way you should filter first
var sortedArray = $filter('orderBy')($scope.events, '-event_date');
var lastDate = sortedArray[sortedArray.length - 1].event_date
hope this gets you on the way.
If you make your server side code return an array sorted by descending date, you could just take the date off the first item in your array. Something like:
events[0].event_date;
Failing that, you could do the sorting on the client side with something like:
events.sort(function(a, b){return new Date(a.event_date) < new Date(b.event_date);});
Then get the value of:
events[0].event_date;

ng-repeat not working properly when using key and value

In my program iam trying to display the resultant array using ng-repeat with key and value but is not working properly.But the output is displayed correctly in console.
I think its a simple mistake but iam not able to figure it out. Here is the code.
app.controller("taglistcontroller",function($scope,MyService1)
{
var photodetails=MyService1.getProperty1();
var array=[];
angular.forEach(photodetails, function(value1)
{
var sample=value1.tag;
angular.forEach(sample, function(value,key)
{
var tagvalue=value;
var temp=array[tagvalue];
if(temp === undefined)
{
array[tagvalue]=1;
}
else
{
temp++;
array[tagvalue]=temp;
}
});
});
$scope.outputtaglist= array;
console.log(array);
});
html code
<H2>Tag list </H2>
<ul>
<li ng-repeat="(key,value) in outputtaglist">
{{key}} {{value}}
</li>
</ul>
Using (key, value) only works if the object to loop over is a key/value object. In this case you are using an array so it only has value's and an index which you can find in $index
<div ng-repeat="value in outputtaglist">
{{$index}} {{value}}
</div>
Furthermore, it looks like your creating your array as if it's an object(technically it is, but thats not the problem right now..), you might just want to instance it with
var array={};

On click How can I cycle through JSON one by one in AngularJS

Creating my first directive as an exercise in angular —making more or less a custom carousel to learn how directives work.
I've set up a Factory with some JSON data:
directiveApp.factory("Actors", function(){
var Actors = {};
Actors.detail = {
"1": {
"name": "Russel Brand",
"profession": "Actor",
"yoga": [
"Bikram",
"Hatha",
"Vinyasa"
]
},
"2": {
"name": "Aaron Bielefeldt",
"profession": "Ambassador",
"yoga": [
"Bikram",
"Hatha",
"Vinyasa"
]
},
"3": {
"name": "Adrienne Hengels",
"profession": "Ambassador",
"yoga": [
"Bikram",
"Hatha",
"Vinyasa"
]
}
};
return Actors;
});
And an actors controller:
function actorsCtrl($scope, Actors) {
$scope.actors = Actors;
}
And am using ng-repeat to display the model data:
<div ng-controller="actorsCtrl">
<div ng-repeat="actor in actors.detail">
<p>{{actor.name}} </p>
</div>
<div ng-click="next-actor">Next Actor</div>
</div>
1) How do I only display the actor's name in the first index of my angular model actors.detail?
2) How do I properly create a click event that will fetch the following index and replace the previous actor.name
User flow:
Russell Brand is Visible
click of next-actor ->Russell Brand's name is replaced with Aaron Bielefeldt
Since you only want the current user, the ng-repeat is not what you want to use, since that would be for each element in the data;
You would want to keep track of the index you are looking at in the scope, and increment that.
<div ng-controller="TestController">
{{data[current].name}}
<div ng-click="Next();"> NEXT! </div>
</div>
Where in the controller we also have these set up, where data is your actors:
$scope.current = 0;
$scope.Next = function() {
$scope.current = ($scope.current + 1) % $scope.data.length;
};
Here's a fiddle where it's done.
I would change my serivce to return a single actor and maintain the index in the controller.
something like this. This is an incomplete solution - you need to take care of cycle etc...

Categories