javascript - angularjs 服务不是函数

标签 javascript angularjs coffeescript 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;
  };
});

和这样的 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/

相关文章:

backbone.js - 在 View 渲染时触发多个事件

javascript - jquery datatables 在页面上导航时在分页表上重置所选行的数据

javascript - 如何使用 javascript 自定义事件而不是 while 循环?

angularjs - 使用 JSON 请求正文测试 Laravel Controller

javascript - AngularJS ng-click 不会从 JQuery 代码中的动态按钮触发

node.js - Mongodb/Mongoose 查询

javascript - 推送到数组不会通过 ng-repeat 指令更新 View 列表

javascript - json为空时如何控制javascript错误

angularjs - 我可以在cordova中使用angular-material吗?

javascript - CoffeeScript 窗口