tldr; I love coffeescript and angular. Looking for feedback on a way
of I'm putting them together using 1.0.rc (with some help from
underscore).
Because my posts always get misformatted I put the code at:
https://gist.github.com/2079970
-------------------------
Okay, so imagine I want to do this:
<div ng:controller="MyController">{{message}}</div>
It looks like it the most recent version of angular, the controller
classes need to explicitly 'scope' their fields to an injected
$scope. So where I used to be able to get away with
class MyController
constructor:->
@message = "Hello World"
Now my class becames:
class MyController
constructor:($scope)->
$scope.message = "Hello World"
I hate typing, so I wrote a function "adaptForAngular" (at bottom)
which takes a class, instantiates it and basically wraps its
properties around the $scope. This function writes a new constructor
into global scope (of the same name as the class) so if you do
adaptForAngular(MyController)
you can then write the controller without the $scope reference, and
use the classname in the ng-controller attribute. Also I can pass in
injections as additional arguments (also a $scope injection
automatically gets pushed in to the injections). If you do
adaptForAngular EditorController, '$http'
it will then call an initializeInjections function on your original
class (I use this instead of a constructor) and pass in to there any
injected arguments (except for scope, which is back to "this" again).
By no longer explictly using scope, TDD is simpler in some cases, plus
your controllers can then be used outside of angular projects.
Thoughts?
Main function below
--------------------
adaptForAngular = (clazz, injections...)->
injections.push "$scope"
@[
clazz.name] = ->
args = _.toArray(arguments)
scope = args.pop()
controller = new clazz()
_.extend scope, controller
scope.initializeInjections? args...
@[
clazz.name].$inject = injections