Providing default functions to AngularJS Directives

Once of the nice things about AngularJS directives is that you can pass functions into the directives using ‘&’ scoping, but providing a default function is a little more tricky.

See the example below:

Whether or not you provide a function with ‘&’, Angular provides the mechanism for executing that function. For example, you can’t treat buttonAction above like the legend attribute. That is, you can’t say:

 ng-click=“buttonAction() || defaultAction()”

There’s always a buttonAction, even if it’s effectively a noop. To get around this, what you do is inspect the attrs object. This object contains the attribute values as the strings they originally are, before Angular interprets them. If buttonAction is defined here, then a function was passed; if not, then no function was provided and a default can be supplied in its place.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>