CoffeeScript and AngularJS

AngularJS and CoffeeScript are a great combination, despite the lack of popularity of CoffeeScript in the AngularJS community. Here are a few ways CoffeeScript makes writing AngularJS code a breeze.

Short Function Definitions

Angular uses a lot of anonymous functions - as such, short function definitions are the biggest timesaver when writing Angular code in CoffeeScript. As an example, lets write an ‘enter key’ directive that evaluates an expression when the enter key is pressed, and after a delay. Not particularly useful, but this should give you a sense of how CoffeeScript and AngularJS work together.

In CoffeeScript, the arrow -> is used to define a function, with the parameters in brackets in front. If a function has no parameters, the brackets are optional, as seen in the function passed to $timeout. You can also see how brackets are optional for calling functions, so long as the function has one or more parameters.

In this short example, we’ve removed the need for the function keyword four times in ten lines of code, and made the code a lot more readable and faster to write. There’s also no need for return statements, as CoffeeScript (like Ruby) automatically returns the value of the last expression in a function.

Automatic Returns

Automatic (or implicit) returns are another feature that makes writing Angular code easier and faster. Here are a few examples where automatic returns come in handy. The differences are not major, but it adds up in a large codebase.

Directives (again)

In this case, we’re using a directive definition object. CoffeeScript’s automatic returns, YAML style object syntax, and short function definitions makes this a lot more readable. This example is taken from the directive guide in the AngularJS docs.

In CoffeeScript, the @ symbol is shorthand for this. So @name becomes this.name. Additionally, prefixing an @ symbol to a function parameter automatically attaches it to this, as seen in the Animal constructor.

Here’s the equivalent handwritten JavaScript. This isn’t identical to the CoffeeScript compiler output, but is functionally equivalent.

The name of the variable in the arguments will be $timeout, so Angular’s dependency injection will still work. Attaching dependencies to the object allows us to access them in methods - such as comeBack.

CoffeeScript classes make dealing with prototypes a lot easier, and that’s without factoring in inheritance.

Controllers

In AngularJS 1.1.5, new syntax for controllers has been introduced. You can watch the egghead.io video about it here, but essentially it allows a class to be passed in as the controller instead of a function with a scope. So, the todolist example on the AngularJS homepage would have the following HTML: