Coffeescript + Angular
Here at Qwilr we’re Coffeescript fanatics. Our Node servers are written in Coffeescript; and all our client-side goodness is Coffeescript as well. We also love Angular. For the most part Angular + Coffeescript go together like the proverbial Peas & Carrots. But there is one gotchya we’ve come across; that had us scratching our heads for awhile…
We were happily crafting directives when this error message popped up:
Referencing DOM nodes in Angular expressions is disallowed.
Imagine we have the following directive:
[prism key=”ExampleScenario” language=”coffeescript”]
When ‘someFunction’ is called; Angular will spit out its ‘Referencing DOM nodes…’ error. Alright, so we’ve got a reproducible error case now what’s happening & how do we fix it?
Unpicking the error
What’s going on here is that CoffeeScript adds an implicit return if none is supplied. This is very much by design (inspired by Ruby), and is an incredibly useful feature. This ‘implicit return’ means that the following:
anotherFunction = -> string = "this is" string + " an implicit return"
Is functionally equivalent to:
anotherFunction = -> string = "this is" string + " an implicit return" return string
So in our example case above, ‘someFunction’ is actually returning the result of ‘element.remove()’ – i.e. its returning a DOM element in Angular expression. This causes an error because Angular’s security mechanisms specifically protect against this behaviour (quoting from the Angular documentation):
Solution: Explicit Return
So to wrap it up: if the last statement of your function is / returns a DOM element; and you’ve run into this error – then just remember to tag on an explicit “return” statement at the bottom of your functions; and you’ll be good to go.
Happy Coding Folks!