Skip to content Skip to sidebar Skip to footer

Arrays In Angular JS

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. $sc

Solution 1:

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,

  • First iterate through the keys array(Object.keys(map)).
  • Then using the key the value can be taken.

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.


Solution 2:

Try this:

$scope.groupedMedia.push({ year: year, response: response.resources[i] });

Now you can do .year and .response


Post a Comment for "Arrays In Angular JS"