【问题标题】:How to display array with ng-repeat如何使用 ng-repeat 显示数组
【发布时间】:2019-08-13 23:46:52
【问题描述】:

我有一个 json 数组,格式为":

{ 
  "School1":  [{"name": "john", "age":"28"},
              {"name": "paul", "age":"27"}],
  "School2":  [{"name": "david", "age":"27"},
               {"name": "sil", "age":"28"}] 
}

如何在 Angular 中使用 ng-repeat 以这种形式在表格中显示:

----------
Name |  Age
----------
School1            
----------
john | 28
----------
paul | 2
----------
School2
----------
david| 27
----------
sil| 28
----------

我会很感激这方面的帮助。

【问题讨论】:

标签: angularjs html-table angularjs-ng-repeat


【解决方案1】:

您可以对您的数据执行一些操作,并可以使用修改后的结构创建另一个对象,以便它可以与 ng-repeat 一起使用,以您想要的形式显示表格。

你可以通过一个例子更好地理解这一点。

这是您要在表格视图中显示的数据

 $scope.testData = { 
      "School1":  [{"name": "john", "age":"28"},
                  {"name": "paul", "age":"27"}],
      "School2":  [{"name": "david", "age":"27"},
                   {"name": "sil", "age":"28"}] 
    }

我们对“testData”执行操作以识别此 JSON 对象中的“School1”和“School2”键。以下行执行该操作。

$scope.keys = Object.keys($scope.testData);

$scope.keys 将是一个键数组:["School1",School2"];

然后您可以迭代键数组并创建另一个可以在 HTML 代码中与 ng-repeat 一起使用的对象。 以下行执行创建该对象(tableData):

$scope.tableData=[];
    //Iterating on array of keys
    $scope.keys.forEach(element => {
           $scope.tableData.push({
                 column : element,
                 data : $scope.testData[element]  //Getting your data from testData 
           });
     });

将进入控制器的最终代码片段将是:

    $scope.testData = { 
        "School1":  [{"name": "john", "age":"28"},
                    {"name": "paul", "age":"27"}],
        "School2":  [{"name": "david", "age":"27"},
                     {"name": "sil", "age":"28"}] 
    }

    $scope.keys = Object.keys($scope.testData);   

    $scope.tableData=[];
    $scope.keys.forEach(element => {
        $scope.tableData.push({
            column : element,
            data : $scope.testData[element]
        });
    });

您的 HTML 代码将如下所示:

<table>
    <tr>
        <th>Name |</th>
        <th>Age</th>
    </tr>
</table>
<table ng-repeat="table in tableData">
    <tr>
        <th>{{table.column}}</th>
    </tr>
    <tr ng-repeat="row in table.data">
        <td>{{row.name}} | </td>
        <td>{{row.age}}</td>
    </tr>
</table>

您绝对可以通过编写自己的 CSS 或包含任何预定义的样式表来美化表格视图。 希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多