問題描述
遍歷對像數組以構建 div 結構 (Iterate over array of object to build a div structure)
我正在嘗試在 Reports 數組中使用角度 ng‑repeat 這些數據創建如下圖所示的結構。我知道我必須使用某種迭代來實現它,但我很迷茫。
$scope.Reports =
[
{ Id: 1, Name: 'Report One', Year: 2016, Month: 5 },
{ Id: 2, Name: 'Report Core', Year: 2016, Month: 5 },
{ Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 },
{ Id: 4, Name: 'Report Moon', Year: 2015, Month: 5 },
{ Id: 5, Name: 'Report Sky', Year: 2015, Month: 2 }
];
我不確定是否我將需要創建另一個數組來存儲一些數據。像這樣的東西
$scope.years = [];
$scope.months = [];
任何幫助將不勝感激。謝謝
參考解法
方法 1:
May be this will give you some idea ‑
<tr ng‑repeat="(key, value) in Reports">
<td> {{key}} </td> <td> {{ value }} </td>
</tr>
Let me know if it works or not
方法 2:
I think You can do it using angular.filter module
<ul ng‑repeat="(key, value) in Reports | groupBy: 'Year'">
{{ key }}
<ul ng‑repeat="(key1, value1) in value | groupBy: 'Month'">
O{{key1}}
<li ng‑repeat="p in value1">
{{p.Name }}
</li>
</ul>
</ul>
JSBin Hope it will Help
方法 3:
You can do this if you can find a way to group by your reports based on date from Controller. Here is the code pen
$scope.getReportGroup = function() {
var groupedReports = {};
angular.forEach($scope.Reports, function(obj, i) {
if (!groupedReports.hasOwnProperty(obj.Year)) {
groupedReports[obj.Year + ''] = [];
}
groupedReports[obj.Year + ''].push(obj);
});
return groupedReports;
}
(by Gilberto Quintero、uzaif、Roli Agrawal、Rishab777)