I have a service like so:
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;
};
});
and a controller like so:
app.controller('writeCtrl', function($scope, Utilities, students) {
$scope.students = students;
$scope.total_age = Utilities.sum($scope.students, 'age');
});
And I keep getting the error
Typerror: Utilities.sum is not a function
Which is confusing because about a dozen other functions under the Utilities service is working fine. What's causing the issue, and how do I get the function to work?
Edit Actual Coffeescript version
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')
Solution:
Coffeescript functions need a return:
App.service 'Utilities', ->
.....
return
Service never returns an object, basically it binds a method or variable to its context; nothing but this
& then it returns a new object
which contains all the things which were binded to this
.
Code
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
});
Update
You should change your coffee script service from
app.service 'Utilities' ->
to
app.service 'Utilities' () ->