Passing variable to directive's attribute

10,779

Angular will interpolate your href attribute after the linking process, however you can observe the attrs. It's in the docs: Directive Attributes

attrs.$observe('href', function ( value ) {
    // here you have the href
});

See it in action: JSFiddle

Share:
10,779
Ben
Author by

Ben

I have just finished a 4-year degree in Physics & Computer Science, and now I am looking to get more into programming. I have been doing Web-Development for seemingly forever. You can talk to me in HTML & CSS, and I also know one thing or another about JS, jQuery, PHP and MySQL. Currently, I am interested in simple 2D game development. I use C++, SDL and OpenGL.

Updated on June 08, 2022

Comments

  • Ben
    Ben about 2 years

    In AngularJS, how can I use a variable within an attribute of a directive?

    Without any directives, this work fine:

    <a 
        href="#/fruits/{{ fruit.short }}/details" 
        title="Back to Fruit details">
        Back
    </a>
    

    Now with directive, this does not work:

    <backButton 
        href="#/fruits/{{ fruit.short }}/details" 
        title="Fruit details">
    </backButton>
    
    
    MyApp.directive( 'backbutton', function() 
    {
        return {
            restrict: 'E',
            link: function( scope, element, attrs ) 
            {
                var href    = attrs.href;
                var title   = attrs.title;
    
                console.log( "href = " + href );    // undefined
                console.log( "title = " + title );  // Fruit details
    
                element.html('<a href="' + href + '" title="Back to ' + title + '">Back</a>');
            }
        };
    });
    

    The directive itself works fine for e.g. href="#/fruits/novariableused". But as soon as I use a variable in the href attribute, its value becomes undefined.

    How can I fix this ?