从AngularJS指令标签中获取字符串值:my-first-directive ="我想要这个"

时间:2015-03-12 09:12:20

标签: angularjs

我想将字符串值传递给我的AngularJS指令而不使用单独的属性,就像这样......

在我的HTML中

<div my-first-directive="number 1"></div>
<div my-first-directive="number 2"></div>
<div my-first-directive="number 3"></div>

和我的JavaScript

.directive('myFirstDirective', function () {
        'use strict';
        return {
            restrict: 'A',
            link: function (scope, element) {
            // now I want the string that follows the directive
            console.log(element[0].attributes[0].nodeValue);
            console.log(element[0].attributes[0].textContent);
            console.log(element[0].attributes[0].value);
            }
        };
    });

现在所有三个console.log方法都输出了我需要的字符串...但是我不确定这不是获得这样一个价值的最好方法,我不需要考虑隔离范围等?我不要求&#34; 2路绑定&#34;什么的是否有更好的或AngularJS获取字符串的方式?

非常感谢提前

1 个答案:

答案 0 :(得分:1)

link()需要一个attrs参数,你会在那里找到你想要的东西:

link: function (scope, element, attrs) {
    // what you want is:
    console.log(attrs.myFirstDirective);
}

属性名称已标准化。