angularjs 服务不是函数
angularjs service is not a function
我有这样的服务:
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');
});
而且我一直收到错误
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 函数需要 return:
App.service 'Utilities', ->
.....
return
服务从不returns一个对象,基本上它将一个方法或变量绑定到它的上下文;除了 this
然后它 returns 一个新的 object
包含所有绑定到 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
});
更新
您应该从
更改您的咖啡脚本服务
app.service 'Utilities' ->
到
app.service 'Utilities' () ->
我有这样的服务:
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');
});
而且我一直收到错误
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 函数需要 return:
App.service 'Utilities', ->
.....
return
服务从不returns一个对象,基本上它将一个方法或变量绑定到它的上下文;除了 this
然后它 returns 一个新的 object
包含所有绑定到 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
});
更新
您应该从
更改您的咖啡脚本服务app.service 'Utilities' ->
到
app.service 'Utilities' () ->