AngularJS嵌套ng对相同元素重复

时间:2015-01-05 14:58:49

标签: javascript json angularjs

有没有办法在AngularJS视图中执行嵌套循环而不创建隐藏的虚拟元素?

这样的事情:

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

或者

<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>

这些都不可能是AFAIK。

我基本上希望我的HTML具有与它所基于的JSON不同的结构。 我怎么能得到这个?有没有办法在没有HTML元素的视图中创建循环?

上面的示例将遍历JSON结构,如下所示:

JSON (为了清晰起见而被剥离了很多)

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

(这是暴雪API对视频游戏“暗黑破坏神3”的实际JSON响应)

1 个答案:

答案 0 :(得分:4)

在渲染之前尝试格式化你的json;

$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

修改

为了提高性能并避免使用角度延伸;

$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);
               })
      })
})