Reputation: 57
i want to display the last activity status of each animal, whereas activity stati and animals may change over time.
First I get this JSON:
$scope.JSON = [
{"Animal" : "Horse", "Status" : "awake", "LastUpdate" : { "$date" : 1473248184519 }},
{"Animal" : "Rabbit", "Status" : "awake", "LastUpdate" : { "$date" : 1473248194240 }},
{"Animal" : "Rabbit", "Status" : "eating", "LastUpdate" : { "$date" : 1473249639255 }},
{"Animal" : "Horse", "Status" : "eating", "LastUpdate" : { "$date" : 1473249652549 }},
{"Animal" : "Horse", "Status" : "sleeping", "LastUpdate" : { "$date" : 1473249656338 }}
]
If an animal is doing something new, the JSON changes automatically, f.e. the rabbit is now sleeping as well as if a new animal appears, f.e. a cow:
$scope.JSON = [
{"Animal" : "Horse", "Status" : "awake", "LastUpdate" : { "$date" : 1473248184519 }},
{"Animal" : "Rabbit", "Status" : "awake", "LastUpdate" : { "$date" : 1473248194240 }},
{"Animal" : "Rabbit", "Status" : "eating", "LastUpdate" : { "$date" : 1473249639255 }},
{"Animal" : "Horse", "Status" : "eating", "LastUpdate" : { "$date" : 1473249652549 }},
{"Animal" : "Horse", "Status" : "sleeping", "LastUpdate" : { "$date" : 1473249656338 }},
{"Animal" : "Rabbit", "Status" : "sleeping", "LastUpdate" : { "$date" : 1473249659505 }},
{"Animal" : "Cow", "Status" : "awake", "LastUpdate" : { "$date" : 1473249659505 }};
]
This JSON expands over time, therefore I want to display only the last value of the different animals in a table like this:
The main problem is, that new animals are added over time into the jSON and should automatically detected and added into the table.
I thought of two Solutions:
1, ng-repeat + filter + limitTo
For this attempt please have a look at this Plunker https://plnkr.co/edit/ftea6vd1qaPZaXGusZAN
This provides me nearly everything except the automatical detection of new animals, any suggestions?
2, creating subset JSONs for each animal
I would create a new JSON subset containing only one animal and ng-repeating over this new JSON (with lastitem). By looping over all animals (how to get all animals? maybe as a foreach list?) I may get each last status of each animal?
Is this better, or even possible?
Upvotes: 1
Views: 93
Reputation: 2265
I would create a method to provide the data to the ng-repeat instead of directly passing the JSON ng-repeat="roll in filtering(JSON)
And on that function would create something like:
function filtering(animals){
var temp = [].concat(animals);
var animalsExisting = []; // To keep track of animals already added
return temp.reverse().filter(function(animal){
var notAdded = animalsExisting.indexOf(animal.Animal) === -1;
if(notAdded) animalsExisting.push(animal.Animal);
return notAdded;
});
}
So would reverse the array so it's start from the last added and filter them just getting the last one added (since it's reversed).
Hope this helps
Upvotes: 1