Reputation: 60644
I have a controller defined like this:
angular.module('myApp')
.controller 'DetailController', ($rootScope, $scope, $routeParams, apiService) ->
onStart = () ->
getData()
getOtherData()
# a bunch of other functions defined here
getData = ->
apiService.get('/detail/' + $routeParams.id).then (result) ->
$scope.data = result.data # really a little bit more involved :)
onStart()
This works.
Now, I want to use some otherService
to do an extra thing in the getData()
function. Let's say that otherService
is defined as
angular.module('myApp')
.factory 'otherService', () ->
doTheThing = -> console.log('did the thing!')
{
doTheThing
}
(this works in other parts of the application).
To use this in my controller, I do this:
angular.module('myApp')
.controller 'DetailController', ($rootScope, $scope, $routeParams, apiService, otherService) ->
onStart = () ->
getData()
getOtherData()
# a bunch of other functions defined here
getData = ->
apiService.get('/detail/' + $routeParams.id).then (result) ->
$scope.data = result.data # really a little bit more involved :)
otherService.doTheThing()
onStart()
i.e. add one argument otherService
at the end of the argument list, and then use it.
This gives me a TypeError
because doTheThing
isn't defined. Debugging, I see that otherService
contains the value false
rather than the service I requested.
Why?
Upvotes: 0
Views: 73
Reputation: 1503
I am not very into Coffeescript, but when i transpile your code using: Try Coffeescript(http://coffeescript.org/), I got:
angular.module('myApp').factory('otherService', function() {
var doTheThing;
doTheThing = function() {
return console.log('did the thing!');
};
return {
doTheThing: doTheThing
};
});
angular.module('myApp').controller('DetailController', function($rootScope, $scope, $routeParams, apiService, otherService) {
var getData, onStart;
onStart = function() {
getData();
return getOtherData();
};
getData = function() {
return apiService.get('/detail/' + $routeParams.id).then(function(result) {
$scope.data = result.data;
return otherService.doTheThing();
});
};
return onStart();
});
I am not sure with returning onStart - because Controller should be ordinary constructor, but never mind i tried to jsbin that and remove unmet dependencies with $q.when and it works.
http://jsbin.com/cubekojuwu/edit?js,console,output
Main thing about factory is that it should return object which should be placed into DI container and your code looks ok. So I suppose your problem is somewhere when transpiling something we can't see here.
Can you provide full "not-working" jsbin? You can put transpiled code into it.
Upvotes: 1