AngularJS服务不是一个函数。

9

我有这样一个服务:

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

1
你的代码缩进正确吗?CoffeeScript是考虑空格的,看起来第3行有一个缩进错误。 - Dan
@DanPantry 你好,当我将代码粘贴到stackoverflow上时,缩进可能会出现问题,但是我的实际代码缩进是正确的。 - Ryan.lay
1个回答

8

服务永远不会返回一个对象,基本上它绑定了一个方法或变量到它的上下文中;除了this之外,它返回一个包含所有绑定到this的内容的新的object

代码

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' () ->

抱歉,这是js2coffee应用程序中的一个打字错误。我正在使用Coffeescript中的@sum =(items,prop)->。 - Ryan.lay
@Ryan.lay 请粘贴您的实际代码,而不是转换后的版本。 - Dan
3
@PankajParkar 给他一些时间,他可能很忙。你只给了他10分钟来更新他的代码。我工作中的大多数会议都持续超过10分钟。 - Dan
@DanPantry 没问题,伙计.. 他可以慢慢来.. :) - Pankaj Parkar
很高兴能帮助你。谢谢。@DanPantry,为什么你认为问题不应该有angularjs-service标签? - Pankaj Parkar
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接