表中具有ng-repeat的2d多级对象

时间:2018-07-04 07:58:29

标签: javascript html angularjs angularjs-ng-repeat

我有一个像这样的2D嵌套对象

$scope.analysisDataNew = [
  {
    "data":{
      "row1":{
          "col1":{
              "subCol1": 10,
              "subCol2": 10,
          },
          "col2":{
              "subCol1": 10,
              "subCol2": 10,
              "subCol3": 10,
          },
          "col3":{
              "subCol1": 10,
          },
      },
      "row2":{
          "col1":{
              "subCol1": 10,
              "subCol2": 10,
          },
          "col2":{
              "subCol1": 10,
              "subCol2": 10,
              "subCol3": 10,
          },
          "col3":{
              "subCol1": 10,
          },
      },
    }
  }
];

我正在尝试使用它为ng-repeat创建表。

到目前为止,我尝试过的是

for (var i = 0; i < $scope.analysisDataNew.length; i++) {

    // row list
    $scope.analysisDataNew[i].xAxis = Object.keys($scope.analysisDataNew[i].data);

    // col list 
    if($scope.analysisDataNew[i].subCol){
        var rows = Object.keys($scope.analysisDataNew[i].data);
        var cols = $scope.analysisDataNew[i].data[rows[0]];
        var colList = [];
        for(var j=0; j<Object.keys(cols).length; j++){
            colList.push({name: Object.keys(cols)[j]});
            colList[j].subcol = [];
            for(var k=0; k < Object.keys(cols[Object.keys(cols)[j]]).length; k++){
                colList[j].subcol.push(Object.keys(cols[Object.keys(cols)[j]])[k]);
            };
        };
        $scope.analysisDataNew[i].colList = colList;
    } else {
        $scope.analysisDataNew[i].colList = Object.keys($scope.analysisDataNew[i].data[$scope.analysisDataNew[i].xAxis[0]]);
    };
    console.log($scope.analysisDataNew[i]);
};

当没有子列时,我很容易打印数据,但是问题出在子列上。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我创建了一个全div解决方案,在此不预先转换数据: https://next.plnkr.co/edit/3fVwZCyyeeHhu6AT

诀窍是使用ng-repeat =“(key,value)in ...”,如此处所述:How to use ng-repeat to iterate over map entries in AngularJS。这样可以遍历地图:

<div class="tbl">
   <div ng-repeat='(rowId, rowValue) in analysisDataNew[0].data' class="tbl-row"> 
      <div ng-repeat="(colId, colValue) in rowValue" class="tbl-cell"> 
         <div class="tbl tbl-inner">
            <div class="tbl-row"> 
               <div ng-repeat="(subColId, subColValue) in colValue" class="tbl-cell"> 
                    {{subColValue}}
               </div>
            </div>
         </div>
      </div>
   </div>
</div>

如果(可能)要显示analysisDataNew中所有条目的所有数据,则需要在外部ng-repeat周围添加一个额外的ng-repeat。