我的控制器中有一个功能,我试图将其重新编写为服务。
该函数读入从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/
答案 0 :(得分:2)
您应该使用
$scope.getEmptyCells = EmptyCellsService.getEmptyCells;
而不是
$scope.getEmptyCells = EmptyCellsService.getEmptyCells();
答案 1 :(得分:1)
我已对您的代码进行了一些更改
<div ng-app="app">
) angular.module("app",[]).factory('EmptyCellsService',
function() {
return {
getEmptyCells: function(len) {
var emptyCells = [];
for(var i = 0; i < 12 - len; i++){
emptyCells.push(i);
}
return emptyCells;
}
};
});
3.更改EventController,如下所示
function EventController($scope,EmptyCellsService) {
$scope.Countries = [{
countryName: "USA",
Details: [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0, 11.0, 12.0,
13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21, 22, 23, 24,
23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31, 32, 33, 34]
}, {
countryName: "UK",
Details: [3.3, 4.4, 5.5, 6.6]
}, {
countryName: "Russia",
Details: [7.7, 8.8, 9.9, 10.0]
}];
$scope.getEmptyCells = EmptyCellsService.getEmptyCells;
}
答案 2 :(得分:1)
首先,您要从函数调用中分配返回值,这不是您想要的,您只需保存对该函数的引用。
$scope.getEmptyCells = EmptyCellsService.getEmptyCells
其次,您的控制器功能对EmptyCellsService一无所知,因为您没有注入依赖项。您只需将参数传递给构造函数:
function EventController($scope, EmptyCellsService) { ...
最后但并非最不重要的是,在提供的小提琴上,你正在调用app.factory
,即使app
没有在任何地方定义......你应该先创建模块:
var app = angular.module('app',[]);
app.factory(...
将你的html绑定到该模块:
<html ng-app="app"