Created
March 8, 2012 22:10
-
-
Save petebacondarwin/2003785 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
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)) |
Author
petebacondarwin
commented
Mar 9, 2012
via email
I was thinking the exact same thing last night! Marvelous !
...from my mobile.
…On Mar 9, 2012 1:08 AM, "Vojta Jina" < ***@***.***> wrote:
We decided to change service -> provider as it actually registers a
provider for service.
And service takes a constructor function (class).
Will get into master soon, here is the build on CI server + related docs:
http://ci.angularjs.org/job/angular.js-vojta/226/artifact/build/pkg/0.10.7-248b9c91/angular-0.10.7-248b9c91.js
http://ci.angularjs.org/job/angular.js-vojta/226/artifact/build/pkg/0.10.7-248b9c91/docs-0.10.7-248b9c91/api/angular.module.AUTO.$provide
So now, you can do:
``` coffee
module.service 'SomeService', SomeServiceClass
```
---
Reply to this email directly or view it on GitHub:
https://gist.github.com/2003785
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment