Explicit Returns: Angular DOM error + Coffeescript.

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…

The Error

We were happily crafting directives when this error message popped up: Referencing DOM nodes in Angular expressions is disallowed.


Example Case

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

Note: Check out the JavaScript that your Coffeescript compiles down to & you’ll see these implicit return statements being generated.

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):

AngularJS restricts access to DOM nodes from within expressions since it’s a known way to execute arbitrary Javascript code.

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!

Dylan Baskind is a Co-Founder & CEO at Qwilr

Dylan Baskind is the CEO and co-founder at Qwilr. He is also a designer, engineer, artist, musician and writer. He plays in this band. Sometimes he makes business focused helpers like like this. He chats with fellow artists and industry here and very, very occasionally posts articles here.