我有这样的服务:
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;
};
});
和这样的 Controller :
app.controller('writeCtrl', function($scope, Utilities, students) {
$scope.students = students;
$scope.total_age = Utilities.sum($scope.students, 'age');
});
我不断收到错误
Typerror: Utilities.sum is not a function
这令人困惑,因为 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
最佳答案
服务从不返回对象,基本上它将方法或变量绑定(bind)到它的上下文;只有 this
& 然后它返回一个新的 object
,其中包含绑定(bind)到 this
的所有东西。
代码
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;
};
//
// ..other utility method should lies here..
//..do your stuff
});
更新
你应该改变你的 CoffeeScript 服务
app.service 'Utilities' ->
到
app.service 'Utilities' () ->
关于javascript - angularjs 服务不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31493181/