我的控制器中有一个函数,我正在尝试将其重写为服务。
该函数读取从 HTML 传入的值的长度(从 1 到 12)。如果传入的值少于 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)">{{ countryDetails }}m</td>
<td ng-repeat="emptyCell in getEmptyCells(country.Details.length)" class="empty">empty</td>
</tr>
</table>
<br>
<table>
<tr ng-repeat="country in Countries">
<th>{{country.countryName}}</th>
<td ng-repeat="countryDetails in country.Details.slice(12, 24)">{{ countryDetails }}m</td>
<td ng-repeat="emptyCell in getEmptyCells(country.Details.length)" class="empty">empty</td>
</tr>
</table>
<br>
<table>
<tr ng-repeat="country in Countries">
<th>{{country.countryName}}</th>
<td ng-repeat="countryDetails in country.Details.slice(24, 36)">{{ countryDetails }}m</td>
<td ng-repeat="emptyCell in getEmptyCells(country.Details.length)" class="empty">empty</td>
</tr>
</table>
</div>
</div>
我的 JS 函数:
$scope.getEmptyCells = function (len) {
var emptyCells = [];
for (var i = 0; i < 12 - len; i++) {
emptyCells.push(i);
}
return emptyCells;
}
我的新服务:
app.factory('EmptyCellsService', function() {
return {
getEmptyCells: function(len) {
var emptyCells = [];
for(var i = 0; i < 12 - len; i++){
emptyCells.push(i);
}
return emptyCells;
}
};
});
我从控制器调用新服务:
$scope.getEmptyCells = EmptyCellsService.getEmptyCells();
但是,空单元格不再显示。
这是我的工作小提琴(使用函数时(服务代码已注释掉):http: //jsfiddle.net/oampz/GkarV/367/