我知道如何使用ng-repeat
创建可变数量的表格单元格,但是如何使用表格行呢?我试图创建一个危险的风格游戏,其中表格行的数量应该等于每列中的问题数量。以下是我的JSON结构:
app.js
$scope.subjects = [
{topic:'politics',question:['How do we fix our bloated economy?'],answer:'We trim the Fiat'}
//more questions & topics
]
问题应该添加到列中,它们应按主题进行组织。我无法站稳脚步;在下面的代码中,我尝试创建等于问题数组长度的表行数,但它不会起作用。
view5.html
<table>
<tr ng-repeat='i in subjects[0].question'>
<!-- <td ng-repeat='subject.question[i] in subjects'></td> should get question for the corresponding topic -->
</tr>
</table>
答案 0 :(得分:0)
您可以使用以下代码。另请转到http://skillcram.com/AngularJS.htm了解一个工作示例。
enter code here
<table border>
<caption>ng-repeat</caption>
<tr ng-repeat="citiTemp in citiTemperatures">
<td>{{ citiTemp.time }}</td>
<td>{{ citiTemp.temp }}</td>
</tr>
</table>
mainApp.controller('example2Controller', function($scope, $http) {
$scope.citiTemperatures = [
{ time:"12:00",
temp:"0"
},
{ time:"02:00",
temp:"05"
},
{ time:"04:00",
temp:"10"
},
{ time:"06:00",
temp:"15"
},
{ time:"08:00",
temp:"20"
}
];
});
答案 1 :(得分:0)
你应该使用如下
<table ng-repeat='subject in subjects'>
<tr>
<td ng-repeat="question in subject.question track by $index">
{{question}}
</td>
</tr>
</table>
我的样本json是
$scope.subjects = [{
topic: 'politics',
question: ['How do we fix our bloated economy?',
'a?', 'How do we fix our bloated economy?'],
answer: 'We trim the Fiat'
}, {
topic: 'politics',
question: ['How do we fix our bloated economy?'],
answer: 'We trim the Fiat'
}, {
topic: 'politics',
question: ['How do we fix our bloated economy?'],
answer: 'We trim the Fiat'
}];
<强> LIVE DEMO 强>
答案 2 :(得分:0)
试试这个,看看我在ng-repeat
中如何使用tr
。
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('app',[]);
app.controller('myCtrl', function myCtrl($scope) {
// body...
$scope.myArray = [{
id:1,
name:'A'
},{
id:2,
name:'B'
},{
id:3,
name:'C'
},{
id:4,
name:'D'
}];
})
</script>
<style type="text/css">
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body ng-controller="myCtrl">
<table>
<tr ng-repeat="x in myArray">
<td>{{ x.id }}</td>
<td>{{ x.name }}</td>
</tr>
</table>
</body>
</html>