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.

Comments

Post your own comment
Sam

Thanks !!

That use case is almost never highligthed in docs and blogs, but very useful !!

Lisa

Thanks! Been looking all over for this piece of information.

Jupo

great, thanks

Anonymous

If your attribute contains text, use '@' instead of '='.

Anonymous

Thanks Peterbe! Thanks Anonymous!

Anonymous

Thank you

matscr

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

Peter

great, thx

Your email will never ever be published.

Previous:
set -ex - The most useful bash trick of the year August 31, 2014 Linux
Next:
Do you curl a lot to check headers? September 5, 2014 Linux
Related by category:
Switching from Next.js to Vite + wouter July 28, 2023 JavaScript
How to SSG a Vite SPA April 26, 2025 JavaScript
An ideal pattern to combine React Router with TanStack Query November 18, 2024 JavaScript
swr compared to @tanstack/react-query August 30, 2024 JavaScript
Related by keyword:
What stumped me about AngularJS May 12, 2013 AngularJS, JavaScript
OpenID, Attribute Exchange, SReg, python-openid and Google April 23, 2010 Python, Web development
The importance of the TITLE attribute April 23, 2008 Web development
Careful when dealing with options in IE April 14, 2006 Web development