javascript - AngularJS 在同一个元素上嵌套了 ngRepeat

标签 javascript json angularjs

有没有一种方法可以在 AngularJS View 中执行嵌套循环而不创建隐藏的虚拟元素?

像这样:

<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 元素的情况下在 View 内创建循环?

上面的例子会像这样遍历 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 响应)

最佳答案

尝试在渲染前格式化你的 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

编辑

为了提高性能,避免使用 Angular 扩展;

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

关于javascript - AngularJS 在同一个元素上嵌套了 ngRepeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782121/

相关文章:

javascript - 如何将组件的 Controller 功能分离到不同的文件中?

javascript - Angularjs未定义错误范围变量

html - AngularJS 函数不运行

javascript - 如何在 AngularJS 中实现服务器端过滤和分页

javascript - 如何使用 AngularJS 填充复选框值列表?

javascript - 用焦点上下文图表线替换空数据 d3js

javascript - 单击鼠标时相机可平滑放大对象位置

php - 使用 json 上传文件和一些数据

android - 检索 JSON 对象时出现空指针异常

javascript - 需要 : var io = require ('socket.io' )(http); 的双参数