我在coffeescript中有这样的服务:
App.service 'CalculateService', ->
@Calculate = (student) ->
if student.type == 'MatureStudent'
student.age + 10
else
student.age + 5
JS版
App.service('CalculateService', function() {
return this.Calculate = function(student) {
if (student.type === 'MatureStudent') {
return student.age + 10;
} else {
return student.age + 5;
}
};
});
和控制器一样:
App.controller 'MarksCtrl', ($scope, $filter, CalculateService, lecture) ->
**create array**
$scope.students = []
angular.forEach $scope.lecture.students, (student) ->
......
$scope.students.push(student)
**save array**
$scope.saveStudents = ->
angular.forEach $scope.students, (student) ->
student.points = CalculateService.Calculate(student)
JS版
App.controller('MarksCtrl', function($scope, $filter, CalculateService, lecture) {
$scope.students = [];
angular.forEach($scope.lecture.students, function(student) {
return $scope.students.push(student);
});
return $scope.saveStudents = function() {
return angular.forEach($scope.students, function(student) {
return student.points = CalculateService.Calculate(student);
});
};
});
我一直在" Typeerror undefined不是一个函数"在我调用CalculateService.Calculate时,我不知道为什么。
我已经尝试了这个并且有效:
$scope.saveStudents = ->
angular.forEach $scope.students, (student) ->
student.points = 2
所以只有在我打电话给服务时才会出现问题。知道我怎么能做这个工作吗?
答案 0 :(得分:3)
看起来您将函数本身作为服务返回。相反,只是不返回函数,服务器由注入器新建,只需将方法附加到其实例并且不返回任何内容。在原始情况下,您必须将其作为CalculateService(student)
尝试:
App.service 'CalculateService', ->
@Calculate = (student) ->
if student.type == 'MatureStudent'
student.age + 10
else
student.age + 5
return
我没有使用过coffeescript,我使用这个transpiler来确定你的服务定义究竟是什么。在怀疑这些问题的时候,控制台记录服务以查看它实际输出的内容(在您的情况下,您应该看到函数本身)。
答案 1 :(得分:1)
考虑到CoffeeScript自动返回最后一行代码,有必要在服务底部放置一个return语句
app.service 'CalculateService', ->
@Calculate = (student) ->
if student.type == 'MatureStudent'
student.age + 10
else
student.age + 5
return