我有这样的JSON数据:
{
"results": [
{
"Header": "header1",
"Sections": [
{
"Name": "sec1"
},
{
"Name": "sec2"
},
{
"Name": "sec3"
}
]
},
{
"Header": "header2",
"Sections": [
{
"Name": "sec4"
}
]
},
{
"Header": "header3",
"Sections": [
{
"Name": "sec5"
}
]
}
]
}
我想以这样的表格布局显示数据:
header1 | header2 | header3
---------------------------------------
sec1|sec2|sec3| sec4 | sec5
我无法使用以下代码执行此操作:
<table>
<tbody>
<tr>
<td ng-repeat="header in results" colspan="{{header.Sections.length}}">
{{header.Header}}
</td>
</tr>
<tr>
<div ng-repeat="header in results">
<td ng-repeat="section in header.Sections">
{{section.Name}}
</td>
</div>
</tr>
</tbody>
</table>
我尝试在<div>
上使用ng-repeat-start但仍无法使其工作。任何帮助表示赞赏。
修改
当前代码的输出是:
header1 | header2 | header3
答案 0 :(得分:0)
angular.module("myApp", [])
.controller("myController", function($scope) {
$scope.results = [{
"Header": "header1",
"Sections": [{
"Name": "sec1"
}, {
"Name": "sec2"
}, {
"Name": "sec3"
}]
}, {
"Header": "header2",
"Sections": [{
"Name": "sec4"
}]
}, {
"Header": "header3",
"Sections": [{
"Name": "sec5"
}]
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="myApp" ng-controller="myController">
<tbody>
<tr>
<td ng-repeat="header in results" colspan="{{header.Sections.length}}">
{{header.Header}}
</td>
</tr>
<tr>
<td ng-repeat="header in results">
<table><tr><td ng-repeat="section in header.Sections">
{{section.Name}}
</td></tr></table>
</td>
</tr>
</tbody>
</table>
每个标题都应该是一个列,每个列应该有一个1行的列表作为列。请参阅代码段并告诉我这是否是您想要的
答案 1 :(得分:0)
关键是按照控制器中所需的方式转换数据。在下面的代码片段中,我添加了一个新函数allSections
,它将检索所有部分的平面列表,以便ng-repeat
指令可以遍历整个列表。我还添加了一个addSection
按钮,以证明当部分数量发生变化时,这会正确更新。帽子提示@AhmedEid首先将代码复制到一个片段中。
angular.module("myApp", [])
.controller("myController", function($scope) {
$scope.results = [{
"Header": "header1",
"Sections": [{
"Name": "sec1"
}, {
"Name": "sec2"
}, {
"Name": "sec3"
}]
}, {
"Header": "header2",
"Sections": [{
"Name": "sec4"
}]
}, {
"Header": "header3",
"Sections": [{
"Name": "sec5"
}]
}];
$scope.allSections = function() {
var sections = [];
for (var i = 0; i < $scope.results.length; i++) {
var column = $scope.results[i];
for (var j = 0; j < column.Sections.length; j++) {
sections.push(column.Sections[j]);
}
}
return sections;
}
$scope.addSection = function(header) {
header.Sections.push({Name: "sec" + (header.Sections.length + 1)});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="myApp" ng-controller="myController">
<tbody>
<tr>
<td ng-repeat="header in results" colspan="{{header.Sections.length}}">
{{header.Header}}
</td>
</tr>
<tr>
<td ng-repeat="section in allSections()">
{{section.Name}}
</td>
</tr>
<tr>
<td ng-repeat="header in results" colspan="{{header.Sections.length}}">
<button ng-click="addSection(header)">Add</button>
</td>
</tbody>
</table>