我正在使用 angular.js 指令来创建可重用的自定义按钮。这是我的第一个指令,所以我一直在仔细阅读文档,但我读过的大多数内容都假设指令代码将对来自 Controller 模型的数据进行操作。但在这种情况下,我想提供按钮文本作为元素文本,如下所示:
<div data-custom-button>Click Me</div>
到目前为止,我所能做到的最接近的就是向 div 添加文本属性。我通过在指令中将 scope.text
设置为“@”来完成此操作。
<div data-custom-button data-text="Click It">Click Me</div>
所以自定义按钮 html 正在工作,但按钮文本是“Click It”,但我希望它是“Click Me”。原因是该应用程序将通过 i18n 支持多种界面语言,它会从所选语言文件中填充元素文本。
这就是我调用该指令的方式:
<div data-custom-button data-text="Click It"
data-i18n="common:controls.login">Click Me</div>
以及customButton.js中的指令代码:
app.directive("customButton", function() {
return {
replace: true,
restrict: 'A',
scope: {
text: '@'
},
templateUrl: "customButton.html"
};
});
还有 customButton.html 文件:
<div class="customButtonWrapper">
<!-- custom html removed for clarity -->
<div class="customButtonText">{{text}}</div>
<!-- custom html removed for clarity -->
</div>
有没有办法引用调用元素的文本?
最佳答案
这就是 ng-transclude 派上用场的地方
将 customButton.html 更改为:
<div class="customButtonWrapper">
<!-- custom html removed for clarity -->
<div class="customButtonText" ng-transclude></div>
<!-- custom html removed for clarity -->
</div>
并指示:
app.directive("customButton", function() {
return {
replace: true,
transclude: true,
restrict: 'A',
templateUrl: "customButton.html"
};
});
示例:jsFiddle
关于javascript - 如何在 angular.js 指令中使用调用元素的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27139936/