Ben
Ben

Reputation: 16659

Passing variable to directive's attribute

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 ?

Upvotes: 3

Views: 10797

Answers (2)

Oliver
Oliver

Reputation: 4471

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

Upvotes: 9

Ticore Shih
Ticore Shih

Reputation: 375

JS:

var app = angular.module("app", []);

var myButtonFn = function() {
  return {
    restrict: "E",
    replace: true,
    transclude: true,
    scope: {href: "="},
    template: "<a ng-href='{{href}}' ng-transclude></a>"
  };
};

app.directive("myButton", myButtonFn);

HTML:

<body ng-app="app">

  <my-button href="'http://www.google.com/'">Button</my-button>

</body>

http://jsbin.com/iwucaw/1/edit

Upvotes: 0

Related Questions