angularjs服务不是一个功能

时间:2015-07-18 16:24:27

标签: 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;
  };
});

和像这样的控制器:

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

我一直收到错误

  

Typerror: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 个答案:

答案 0 :(得分:7)

服务永远不会返回一个对象,基本上它将一个方法或变量绑定到它的上下文;只有<!DOCTYPE html> <html> <head> <meta charset="US-ASCII"> <title>Insert title here</title> </head> <body> <script src="http://www.java.com/js/deployJava.js"></script> <script> var attributes = { codebase : 'ProjetoICD', code : 'AppletImage.class', archive : 'Java2Demo.jar', width : 710, height : 540 }; var parameters = { fontSize : 16 }; var version = '1.7'; deployJava.runApplet(attributes, parameters, version); </script> </body> </html> &amp;然后它会返回一个新的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
});

app.service 'Utilities' ->