所以我在名为“MainController”的 Controller 中定义了以下 javascript 对象集合:
$scope.records = [
{
id: 100,
name: 'Item Shipping 100',
minute: 7
},
{
id: 101,
name: 'Item Shipping 101',
minute: 9
},
{
id: 102,
name: 'Item Shipping 102',
minute: 15
}
];
我想将此集合绑定(bind)到 HTML 表格,每个单元格中的范围为 10 分钟:
0 - 9
10 - 19
20 - 29
30 - 39
40 - 49
50 - 59
每个单元格代表一个 10 分钟范围,在每个单元格中我只想显示记录集合中属于单元格内每个范围的项目,这就是我现在正在做的方式,有没有更好的方法去做这个?我问的原因是我有很多行要添加,我不想多次重复此代码,可能有更好的方法来绑定(bind)它。
<div ng-controller="MainController">
<table class="table">
<thead>
<tr>
<th>0 - 9</th>
<th>10 - 19</th>
<th>20 - 29</th>
<th>30 - 39</th>
<th>40 - 49</th>
<th>50 - 59</th>
</tr>
</thead>
<tbody>
<tr class="even-row">
<td>
<div class="record" ng-repeat="item in records" ng-if="item.minute >= 0 && item.minute <= 9">
<div>{{ item.id }}</div>
<div>{{ item.name }}</div>
</div>
</td>
<td>
<div class="record" ng-repeat="item in records" ng-if="item.minute >= 10 && item.minute <= 19">
<div>{{ item.id }}</div>
<div>{{ item.name }}</div>
</div>
</td>
<td>
<div class="record" ng-repeat="item in records" ng-if="item.minute >= 20 && item.minute <= 29">
<div>{{ item.id }}</div>
<div>{{ item.name }}</div>
</div>
</td>
<td>
<div class="record" ng-repeat="item in records" ng-if="item.minute >= 30 && item.minute <= 39">
<div>{{ item.id }}</div>
<div>{{ item.name }}</div>
</div>
</td>
<td>
<div class="record" ng-repeat="item in records" ng-if="item.minute >= 40 && item.minute <= 49">
<div>{{ item.id }}</div>
<div>{{ item.name }}</div>
</div>
</td>
<td>
<div class="record" ng-repeat="item in records" ng-if="item.minute >= 50 && item.minute <= 59">
<div>{{ item.id }}</div>
<div>{{ item.name }}</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
谢谢!
最佳答案
您可以在 Controller 中定义范围,例如:
$scope.ranges = [];
$scope.rangeStep = 10;
for (var i = 0; i < 60; i += step) {
ranges.push([i, i + step - 1]);
}
然后在您的 HTML 中,仅写入第一个 ,例如:
<tr>
<th ng-repeat="range in ranges">{{ range[0] }} - {{ range[1] }}</th>
</tr>
并且只有一个td
,例如:
<tr>
<td ng-repeat="range in ranges">
<div class="record" ng-repeat="item in records" ng-if="item.minute >= range[0] && item.minute <= range[1]">
<div>{{ item.id }}</div>
<div>{{ item.name }}</div>
</div>
</td>
</tr>
这应该可以解决问题,然后如果您想要更多列或不同的步骤,只需在 Controller 中编辑 ranges
声明即可。
关于javascript - AngularJS - 按范围将对象集合绑定(bind)到 HTML 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029533/