将变量传递给指令属性

时间:2013-06-09 11:49:23

标签: angularjs angularjs-directive

在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

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:8)

Angular会在链接过程后插入你的href属性,但你可以观察到attrs。它位于文档中:Directive Attributes

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

查看实际操作:JSFiddle

答案 1 :(得分: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

相关问题