AngularJS nested ngRepeat on the same element

Is there a way to do nested loops in AngularJS view without creating hidden dummy elements?

Something like that:

<ul>
    <li ng-repeat="gem in activeHero.gems"
        ng-repeat="(key, value) in gem.attributes"
        ng-repeat="attr in value">
            {{attr.text}}
    </li>
</ul>

      

or

<ul>
    <li ng-repeat-start="gem in activeHero.gems"
        ng-repeat-start="(key, value) in gem.attributes"
        ng-repeat="attr in value">
            {{attr.text}}
    </li ng-repeat-end 
         ng-repeat-end>
</ul>

      

None of these are possible AFAIK.

Basically I want my HTML to have a different structure than the JSON it is based on. How could I achieve this? Is there a way to create loops inside a view without an HTML element?

The above examples will overlap the JSON structure like this:

JSON (stands out a lot for clarity)

"activeHero" = {
  "gems" : [ {
    "attributes" : {
      "primary" : [ {
        "text" : "+220 Intelligence"
      } ],
      "secondary" : [ ],
      "passive" : [ ]
    }
  }, {
    "attributes" : {
      "primary" : [ {
        "text" : "+220 Intelligence"
      } ],
      "secondary" : [ ],
      "passive" : [ ]
    }
  }, {
    "attributes" : {
      "primary" : [ {
        "text" : "+160 Intelligence"
      } ],
      "secondary" : [ ],
      "passive" : [ ]
    }
  } ]
}

      

(This is a real JSON response from the Blizzard API for the "Diablo 3" video game)

+3


source to share


1 answer


Try to format json before rendering;

$scope.formattedData = [];
angular.forEach(activeHero.gems, function(value, key){
      var item = {
         //set filed you want
      }
      angular.forEach(value.atrtibutes, function(value2, key2){
               item['propyouwant'] = value2[propyouwant]
               angular.forEach(value2.primary, function(value3, key3){
                      item['propyouwant'] = value3[propyouwant]
                     $scope.formattedData.push(angular.extend({}, item));
               })
      })
})

//now you can render your data without somersould

      

EDIT



To improve performance and prevent the use of angular extend;

$scope.formattedData = [];
angular.forEach(activeHero.gems, function(value, key){

      angular.forEach(value.atrtibutes, function(value2, key2){
               angular.forEach(value2.primary, function(value3, key3){
                     //start build your item here
                      var item = {
                        prop1: value['prop'],
                        prop2: value2['prop']
                       }
                     //not required extend item;
                     $scope.formattedData.push(item);
               })
      })
})

      

+4


source







All Articles