Skip to content

Instantly share code, notes, and snippets.

@petebacondarwin
Created March 8, 2012 22:10
Show Gist options
  • Save petebacondarwin/2003785 to your computer and use it in GitHub Desktop.
Save petebacondarwin/2003785 to your computer and use it in GitHub Desktop.
###
Currently if you want to use a coffee script class for an AngularJS service
the syntax for the dependency injection is a bit clunky: you have to define
the dependencies in multiple places
###
class SomeServiceClass
constructor: (@$dep1, @$dep2)->
# Initialize the service
someMethod: ()=>
# Do something
angular.module('SomeModule', [])
.factory("SomeService", ['$dep1', '$dep2', ($dep1, $dep2)->new SomeServiceClass($dep1, $dep2)])
###
This is a lot of typing and prone to error when you change the dependencies
It would be better if we could make use of the $inject form.
Currently this is not possible out of the box if using module.factory, since it expects a callable function
not a "class" function that should be instantiated.
We can get halfway by creating a helper
###
class SomeService
@$inject: ['$dep1', '$dep2'] # Dependencies only here and in the constructor
constructor: (@$dep1, @$dep2)-> # Right next to each other!
# Initialize the service
someMethod: ()=>
# Do something
# This helper wraps the class instantiation in a function and a dependency array
injectionHelper = (klass)->
klass.$inject.push (args...)-> new klass(args...)
# Now we can just wrap our class in our helper
angular.module('SomeModule', [])
.factory("SomeService", injectionHelper(SomeServiceClass))
@petebacondarwin
Copy link
Author

petebacondarwin commented Mar 9, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment