angularjs服务不是一个功能

Rya*_*lay 9 javascript coffeescript angularjs angularjs-service

我有这样的服务:

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;
  };
});
Run Code Online (Sandbox Code Playgroud)

和这样的控制器:

app.controller('writeCtrl', function($scope, Utilities, students) {
  $scope.students = students;
  $scope.total_age = Utilities.sum($scope.students, 'age');
});
Run Code Online (Sandbox Code Playgroud)

而且我一直在收到错误

Typerror:Utilities.sum不是一个函数

这是令人困惑的,因为公用事业服务下的十几个其他功能工作正常.是什么导致了这个问题,我该如何让这个功能起作用?

编辑 实际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')
Run Code Online (Sandbox Code Playgroud)

解:

Coffeescript函数需要返回:

App.service 'Utilities', -> 
  .....
  return
Run Code Online (Sandbox Code Playgroud)

Pan*_*kar 7

服务永远不会返回一个对象,基本上它将方法或变量绑定到它的上下文; 什么,但this然后它返回一个新的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
});
Run Code Online (Sandbox Code Playgroud)

更新

你应该改变你的咖啡脚本服务

app.service 'Utilities' ->
Run Code Online (Sandbox Code Playgroud)

app.service 'Utilities' () ->
Run Code Online (Sandbox Code Playgroud)

  • @PankajParkar给他时间.他可能很忙.你只给了他10分钟来更新他的代码.我工作的大多数会议都持续了10多分钟. (3认同)