我有一个简单的 ng-repeat,它循环遍历一个 JSON 文件,其中包含国家/地区列表以及有关该国家/地区的详细信息,例如货币、特定月份的人口(本例中为 24)
我的 ng-repeat 成功循环前 12 个月,并在满足 ng-switch 条件时显示相应的文本。
此外,在前 12 个月内,如果没有可用数据,则单元格中会显示“空”。
但是,由于我使用 2 个 ng-repeats
和 slice
,我似乎无法让我的 getEmptyCells
函数工作/显示空对于大于 12 的月份。
HTML:
<div ng-app="">
<div ng-controller="EventController">
<table>
<tr ng-repeat="country in Countries">
<th>{{country.countryName}}</th>
<td ng-repeat="countryDetails in country.Details.slice(0, 12)" ng-switch="countryDetails">
<span ng-switch-when="11">Medium</span>
<span ng-switch-when="22">Large</span>
<span ng-switch-when="33">Larger</span>
<span ng-switch-when="44">Very Large</span>
<span ng-switch-default>Error</span>
</td>
<td ng-repeat="emptyCell in getEmptyCells(country.Details.length)" class="empty">
empty
</td>
</tr>
<tr ng-repeat="country in Countries">
<th>{{country.countryName}}</th>
<td ng-repeat="countryDetails in country.Details.slice(13, 24)" ng-switch="countryDetails">
<span ng-switch-when="11">Medium</span>
<span ng-switch-when="22">Large</span>
<span ng-switch-when="33">Larger</span>
<span ng-switch-when="44">Very Large</span>
<span ng-switch-default>Error</span>
</td>
<td ng-repeat="emptyCell in getEmptyCells(country.Details.length)" class="empty">
empty
</td>
</tr>
</table>
</div>
</div>
js:
function EventController($scope) {
$scope.Countries = [
{
countryName:"USA",
Details:[11,22,33,44,55,66,77,88,99,00,01,02,11,22]
},
{
countryName:"UK",
Details:[33,44,55,66]
},
{
countryName:"Russia",
Details:[77,88,99,00]
}
];
$scope.getEmptyCells = function(len){
var emptyCells = [];
for(var i = 0; i < 12 - len; i++){
emptyCells.push(i);
}
return emptyCells;
}
}
我的 fiddle :http://jsfiddle.net/oampz/8hQ3R/
更新的 fiddle :http://jsfiddle.net/oampz/8hQ3R/2/尝试使用 2 个函数
更新的 fiddle :http://jsfiddle.net/oampz/8hQ3R/3/在 getEmptyCells2 中传递切片
最佳答案
您这里有 2 个问题。
首先,您没有将正确的数字传递给 slice方法用于大于 12 的月份。第一个参数是开始索引。在前十二个月中,您使用了 country.Details.slice(0, 12)
,这意味着从索引 0
开始,到索引 12
结束,定义为
Zero-based index at which to end extraction. slice extracts up to but not including end.
因此,您在前 12 个月中使用索引 0-11(总共 12 个元素)。为了显示接下来的 12 个月,您需要从索引 12 开始,而不是 13。
ng-repeat="countryDetails in country.Details.slice(12, 24)"
现在您的第二个问题是您没有为第二个表格获得正确数量的“空”单元格。原因是因为您没有考虑到您正在查看接下来 12 个月,而不是前 12 个月。解决此问题的最简单方法是从您使用的长度参数中减去 12您正在显示接下来的 12 个月。
<td ng-repeat="emptyCell in getEmptyCells(country.Details.length-12)" class="empty">
empty
</td>
但是如果您这样做,请确保更新您的 getEmptyCells
函数以解决这一问题,并在得到负数时进行调整
$scope.getEmptyCells = function(len){
var emptyCells = [];
if (len<0) { len = 0; }
for(var i = 0; i < 12 - len; i++){
emptyCells.push(i);
}
return emptyCells;
}
这是更新的 fiddle :http://jsfiddle.net/callado4/8hQ3R/5/
关于javascript - AngularJS - 当使用切片两次时数据不可用时,ng-repeat 显示空单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23696156/