将变量传递给指令的属性

Ben*_*Ben 3 angularjs angularjs-directive

在AngularJS中,如何在指令的属性中使用变量?

没有任何指令,这工作正常:

<a 
    href="#/fruits/{{ fruit.short }}/details" 
    title="Back to Fruit details">
    Back
</a>
Run Code Online (Sandbox Code Playgroud)

现在有了指令,这不起作用:

<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>');
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

该指令本身适用于例如href="#/fruits/novariableused".但是只要我在href属性中使用变量,它的值就会变为undefined.

我怎样才能解决这个问题 ?

Oli*_*ver 8

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
});
Run Code Online (Sandbox Code Playgroud)

See it in action: JSFiddle