An AngularJS directive with itself as the attribute

03 September 2014   8 comments   AngularJS, Javascript

Powered by Fusion×

Because this took me quite a while to figure out, I thought I'd share in case somebody else is falling into the same pit of confusion.

When you write an attribute directive in angularjs you might want to have it fed by an attribute value.
For example, something like this:

<div my-attribute="somevalue"></div>

How then do you create a new scope that takes that in? It's not obvious. Any here's how you do it:

app.directive('myAttribute', function() {
    return {
        restrict: 'A',
        scope: {
            myAttribute: '='
        template: '<div style="font-weight:bold">{{ myAttribute | number:2 }}</div>'

The trick to notice is that the "self attribute" because the name of the attribute in camel case.

Thanks @mythmon for helping me figure this out.

Follow @peterbe on Twitter


Thanks !!

That use case is almost never highligthed in docs and blogs, but very useful !!
Thanks! Been looking all over for this piece of information.
great, thanks
If your attribute contains text, use '@' instead of '='.
Thanks Peterbe! Thanks Anonymous!
Thank you
Im new to angularjs! THIS WAS GOLD! Been struggeling with passing values in directives. Thanks alot for this info that is nowhere to be found but here
great, thx
Thank you for posting a comment

Your email will never ever be published

Related posts

set -ex - The most useful bash trick of the year 31 August 2014
Do you curl a lot to check headers? 05 September 2014
Related by Keyword:
What stumped me about AngularJS 12 May 2013
OpenID, Attribute Exchange, SReg, python-openid and Google 23 April 2010
The importance of the TITLE attribute 23 April 2008
Careful when dealing with options in IE 14 April 2006
Related by Text:
OpenID, Attribute Exchange, SReg, python-openid and Google 23 April 2010
One-way data bindings in AngularJS 1.3 11 December 2014
Why is it important to escape & in href attributes in tags? 11 November 2014
Lesson learnt with creating DOM element with jQuery 04 April 2008
Don't that this or bind 12 April 2016