Reputation: 44715
What is the best practice in creating angular controllers using coffee script classes? I've been googling for a while, but haven't found a really nice solution so far.
According to this article author suggest the following approach:
angular.module('myApp').controller 'SomeCtrl',
class SomeCtrl
someModels: -> ...
However, it is not clarified how to make any injections to such a controller. Since coffee is automatically moving all methods to constructor's prototype I will not be able to access injected services within those methods.
So far the only way to get around this is:
angular.module('myApp').controller 'SomeCtrl',
class SomeCtrl
@$inject: ['SomeService']
constructor: (someService) ->
@load = ->
# access to someService
Obviously this is quite ugly, not to mention memory-inefficient.
So the question is, what is the best way to define angular controller using Coffee goodies?
EDIT:
There is another option to explicitly use an injector:
app = angular.module('myApp')
injector = angular.injector([app.name])
injector.invoke ['SomeService', (SomeService) ->
app.controller 'SomeCtrl',
class SomeCtrl
foo: 'bar'
func: ->
# Prototype function with access to SomeService without exposing it in API.
]
This however makes code order dependent and is ugly as hell.
What I would be looking for ideally is some sort of way to define a controller as a factory - instead of passing constructor function I would like to pass a function which is to return a constructor. Is anything like this possible?
Upvotes: 1
Views: 482
Reputation: 58619
First define the class, adding required services in the constructor...
class SomeCtrl
constructor: (someService)-> alert someService 9
Next, attach as controller to app...
angular.module('myApp').controller 'SomeCtrl', SomeCtrl
<div ng-app="myApp">
<div ng-controller="SomeCtrl">
</div>
</div>
... and ...
angular.module 'myApp', []
angular.module('myApp').factory 'someService', ->
(x)-> x * x;
class SomeCtrl
constructor: (someService)-> alert someService 9
someModels: ->
angular.module('myApp').controller 'SomeCtrl', SomeCtrl
Upvotes: 1