How to reference a function in Angular's directives

2015-10-05 | #angular, #javascript, #solution, #webdev

It's quite straightforward how to couple a directive's isolated scope to values of the context scope, but the case on how to do this with a function is a little hidden and also unintuitive.

Normally you would think that the following should work:

<my-directive foobar-function="fooBar" ...

scope : { foobar : '=foobarFunction' ...

var stuff = foobar(5, 'foobar');

But nope, this will do exactly nothing. Instead you'll have to use Angular's way of binding a runtime evaluated value in a nearly undocumented way. You'll be more successful by doing this:

<my-directive foobar-function="fooBar(param1, param2)" ...

scope : { foobar : '&foobarFunction' ...

var stuff = foobar({param1 : 5, param2 : 'foobar'});

So you define your scope method as being provided arbitrarily named params from a yet undefined context (that of the expression evaluation). You then define this definition as an expression to be evaluated on call by using "&" instead of "=". At last you provide the evaluation wrapper function with a map of your named params to supply your definition with, essentially just relaying the values one level.

Highly intuitive! But most likely more robust and performant then the direct approach.