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
In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services. One of them is the $location service.
In the service we are using other inbuilt angular service $http to make the call to the service. To use the $http service, we have to pass this as dependency to the service factory() method. Once service is created, let us create the controller which will use the service to perform the operations. var myApp = angular.
A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.
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' () ->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With