CoffeeScript Classes Play Nicely with AngularJS Factories
28 Jul 2013
One of CoffeeScript’s many virtues is built-in support for classes, inheritance, and super via the class
keyword. One of AngularJS’s many virtues is built-in dependency injection of services via factory functions.
How do you use CoffeeScript classes and AngularJS factories together? There is no trickery needed at all. You just define your class like this:
app.factory "Ticket", ->
class Ticket
constructor: (@price, @count) ->
amount: ->
@price * parseInt(@count, 10)
Now you can inject a Ticket
factory into, for instance, your controller context and use it like so:
app.controller "MainCtrl", ($scope, Ticket) ->
$scope.ticket = new Ticket(100, 2)
And use it in a template if you like:
<div ng-controller="MainCtrl">
<p>That'll be {{ticket.amount()}} pesos, amigo</p>
</div>
Thanks for playing nice, you two.