我是AngularJS的新手,目前停留在标题中的说明上,即在表中动态生成列。我的情况是:从Python(更具体而言,是Django),我传递了dict和list:list包含列名(“ Week X”,其中X对应于周数),而dict看起来像这样:
data : {
'Person A': {
'Week 1' : {
'Task 1': True,
'Task 2': False,
},
'Week 2' : {
'Task 1': True,
'Task 2': True,
},
},
'Person B': {
'Week 1' : {
'Task 1': True,
'Task 2': False,
},
'Week 2' : {
'Task 1': False,
'Task 2': False,
},
},
}
随着周数的变化,这种结构也在变化。我想动态生成它,所以它看起来像这样:
首先想到的是创建列模板,然后对列表中的每个元素重复该模板。但这是我遇到问题的地方-我只是做不到,而每一个新列都添加到上一个列的下面。我的代码如下:
<table>
<thead>
<th>Person ID</th>
<th ng-repeat="week in weeks order by $index">
<tr>
<td>{{ week }}</td>
</tr>
<tr>
<td>Task 1</td>
<td>Task 2</td>
</tr>
</th>
</thead>
<tbody>
<tr ng-repeat='person in data'>
<td>{{ person }}</td>
<td>{{ Task 1 }}</td>
<td>{{ Task 2 }}</td>
</tr>
</tbody>
</table>
另外,我想遍历任务,这意味着我想动态创建并用特定人员每特定周的数据填充列,但我不知道如何-我不能只放{{ 1}}中的ng-repeat
中,我不知道我可以使用哪个html标签来实现这一目标。
答案 0 :(得分:1)
angular.module('app', []).controller('ctrl', function($scope) {
$scope.data = {
'Person A': {
'Week 1': { 'Task 1': true, 'Task 2': false },
'Week 2': { 'Task 1': true, 'Task 2': true }
},
'Person B': {
'Week 1': { 'Task 1': true, 'Task 2': false },
'Week 2': { 'Task 1': false, 'Task 2': false }
}
};
$scope.weeks = [];
for (var personName in $scope.data) {
var person = $scope.data[personName];
for (var weekName in person) {
var week = person[weekName];
var weekScope = {
name: weekName,
tasks: []
};
$scope.weeks.push(weekScope);
for (var taskName in week)
weekScope.tasks.push(taskName)
}
break;
}
})
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
.center{
text-align:center;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div ng-app='app' ng-controller='ctrl'>
<table>
<thead>
<tr>
<td rowspan='2'>Person ID</td>
<td ng-repeat='week in weeks' class='center' colspan='{{week.tasks.length}}'>
{{week.name}}
</td>
</tr>
<tr>
<td ng-repeat-start='week in weeks' hidden></td>
<td ng-repeat-end ng-repeat='task in week.tasks'>{{task}}</td>
</tr>
</thead>
<tbody>
<tr ng-repeat='(personName, person) in data'>
<td>{{personName}}</td>
<td ng-repeat-start='week in weeks' hidden></td>
<td ng-repeat-end ng-repeat='task in week.tasks'>
{{person[week.name][task]}}
</td>
</tr>
</tbody>
</table>
</div>