Reputation: 152
Am new to angular JS, I am pushing elements in an array and then want to display in the html using ng-repeat.
$scope.groupedMedia = [];
//Adding elements through a for loop.
$scope.groupedMedia[year].push(response.resources[i]);
console.log($scope.groupedMedia);
//The above console displays the following,
//[2014_January: Array[5], 2013_December: Array[95]]
So in my HTML,
<div ng-repeat="group in groupedMedia">
<div ng-repeat="file in group">
<p>{{file.lastModified}}</p>
</div></div>
I observe that the groupedMedia array in the html is empty and hence not displaying any data. I also need to display the items in the array in the same order as i push it. Any tips to solve this will be very helpful.
Upvotes: 3
Views: 1681
Reputation: 4022
Ideally groupedMedia obj has to be restructured to an year map(year as key and resources as value). Using an array for random numbers is not recommended and has to be avoided Sample JS:
$scope.groupedMedia = {};
$scope.groupedMedia[year] = response.resources[i];
console.log($scope.groupedMedia); //This will provide an output like below.
//{'2014_January': Array[5], '2013_December': Array[95]}
In html, First iteration will be though the groupMedia map. With ng-repeat one can iterate through a map and refer the key/value pair of the map in the child list. And the second one will the the resources array.
Sample HTML code:
<div ng-repeat="(group, files) in groupedMedia">
<div ng-repeat="file in files">
<p>{{file.name + ': '+ file.lastModified}}</p>
</div>
</div>
have found a way to maintain the order of the map,
Object.keys(map)
). JS addition:
$scope.groupKeys = function(data){
return Object.keys(data);
}
HTML addition:
<div ng-repeat="key in groupKeys(groupedMedia)">
{{key}}
<div ng-repeat="file in groupedMedia[key]">
<p>{{file.name + ': '+ file.lastModified}}</p>
</div>
</div>
I have update the plunker to reflect the same. Though would be really interested to know if there is an alternate way. Sample Demo: http://plnkr.co/edit/JfqIoZMQmFz2cwFvce2K?p=preview The above plunker has a demo with the above code. Have a look and let me know if it helps.
Upvotes: 1
Reputation: 75854
Try this:
$scope.groupedMedia.push({ year: year, response: response.resources[i] });
Now you can do .year
and .response
Upvotes: 0