【问题标题】:How to group and rowspan in angular js如何在角度js中分组和行跨度
【发布时间】:2017-07-11 02:26:44
【问题描述】:
我在下面给出了一个 Json
[{
groupName: "Group 1",
[{
name: "Item 1"
}, {
name: "Item 2"
}]
},
{
groupName: "Group 2",
[{
name: "Item 3"
}, {
name: "Item 4"
}]
}]
我需要一个像 here 所示的表格,如何在 Angular js 中实现。
【问题讨论】:
标签:
javascript
html
angularjs
html-table
【解决方案1】:
您必须使用ng-repeat 指令才能将render 信息转入table。
var myApp = angular.module('myApp', []);
function myCTRL($scope) {
$scope.groups = [{
groupName: "Group 1",
sub: [{
name: "Item 1"
}, {
name: "Item 2"
}]
},
{
groupName: "Group 2",
sub: [{
name: "Item 3"
}, {
name: "Item 4"
}]
}
];
}
td,th{
border:1px solid grey;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCTRL">
<table>
<tr>
<th>Group</th>
<th>Items</th>
</tr>
<tr ng-repeat="group in groups" >
<td>{{group.groupName}}</td>
<td >
<table>
<tr ng-repeat="subgroup in group.sub">
<td>{{subgroup.name}}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
【解决方案2】:
这是我的解决方案
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.data = [{
groupName: "Group 1",
nestedData: [{
name: "Item 1"
}, {
name: "Item 2"
}]
},
{
groupName: "Group 2",
nestedData: [{
name: "Item 3"
}, {
name: "Item 4"
}]
}
];
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<table class="table">
<thead>
<th>Name</th>
<th>Nested name</th>
</thead>
<tbody ng-repeat="item in data">
<tr ng-repeat="nestedItem in item.nestedData">
<td rowspan="{{item.nestedData.length}}" ng-hide="$index == 1">{{item.groupName}}</td>
<td>{{nestedItem.name}}</td>
</tr>
</tbody>
</table>
</div>
【解决方案3】:
我保留了您的 JSON 结构,但只是将名称 vals 分配给子数组:
angular.module('app', []).controller('ctrl', function($scope) {
$scope.data = [{
groupName: "Group 1",
vals: [{
name: "Item 1"
}, {
name: "Item 2"
}]
}, {
groupName: "Group 2",
vals: [{
name: "Item 3"
}, {
name: "Item 4"
}]
}];
});
table,
th,
td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app="app" ng-controller="ctrl">
<thead>
<td><strong>Group</strong></td>
<td><strong>Items</strong></td>
</thead>
<tbody ng-repeat="d in data">
<tr>
<td rowspan="{{d.vals.length}}">{{d.groupName}}</td>
<td>{{d.vals[0].name}}</td>
</tr>
<tr ng-repeat="v in d.vals" ng-if="$index > 0">
<td>{{v.name}}</td>
</tr>
</tbody>
</table>