我有这样一个服务:
app.service('Utilities', function() {
this.sum = function(items, prop) {
var count, total;
total = 0;
count = 0;
if (items === null) {
total = 0;
}
while (count < items.length) {
total += items[count][prop] * 1 || 0;
count++;
}
return total;
};
});
并使用如下控制器:
app.controller('writeCtrl', function($scope, Utilities, students) {
$scope.students = students;
$scope.total_age = Utilities.sum($scope.students, 'age');
});
我一直遇到这个错误:
类型错误:Utilities.sum不是一个函数
这很困惑,因为 Utilities 服务下的其他大约十几个函数都正常工作。是什么导致了这个问题,我该如何让这个函数正常工作呢?
编辑 实际的 Coffeescript 版本:
app.service 'Utilities', ->
@sum = (items, prop) ->
total = 0
count = 0
if items == null
total = 0
while count < items.length
total += (items[count][prop]*1 || 0)
count++
return total
app.controller 'writeCtrl', ($scope, Utilities, students) ->
$scope.students = students
$scope.total_age = Utilities.sum($scope.students, 'age')
解决方案:
Coffeescript函数需要返回值:
App.service 'Utilities', ->
.....
return