3

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

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

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

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

<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>');
        }
    };
});

该指令本身适用于例如href="#/fruits/novariableused"。但是,一旦我在href属性中使用了一个变量,它的值就会变成undefined.

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

4

2 回答 2

9

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

于 2013-06-10T08:38:59.050 回答
0

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

于 2013-06-10T09:23:33.777 回答