如何在指令中获得{{text}}?

时间:2014-11-21 09:41:52

标签: javascript angularjs directive

我有这样的代码:

<my-button>{{text}}</my-button>  (The 'text' is not so sure, can be the other like: 'mytext')

myApp.directive("myButton", function(){
    function linkFunc(scope, element, attrs){
        //How to get the {{}} variable name and value?
        //not always '{{text}}' can be {{text1}}  {{text2}}
    }
    return {
        link: linkFunc,
        restrict: "E",
        template: "<button></button>,
        transclude: true,
        replace: true
    }
});

我知道我可以使用element.text()获取文本并在指令中重新编译它。还有其他办法吗?

2 个答案:

答案 0 :(得分:4)

你需要像你一样将你的指令标记为'transclude',但你还需要一个内容的插入点。在这种情况下,它只是在按钮内部,所以你可以做这样的事情:

app.directive('myButton', function () {
    return {
        restrict: 'E',
        template: '<button ng-transclude></button>',
        transclude: true
    }
});

Fiddle

答案 1 :(得分:3)

您可以尝试将其作为参数传递:

<my-button text="someText"></my-button> or
<my-button text="{{text}}"></my-button> 

myApp.directive('myButton', function(){
    function linkFunc(scope, element, attrs){
        //How to get the {{}} variable name and value?
        //not always '{{text}}' can be {{text1}}  {{text2}}
    }
    return {
        scope: { text: '@' },
        link: linkFunc,
        restrict: "E",
        template: "<button>{{text}}</button>,
        transclude: true,
        replace: true
    }
});