所以我关注this EggHead.io tutorial在自定义组件上,我遇到了这个问题。声明指令时,例如:
angular.module('myApp', [])
.directive('myDir', function(){
return {
restrict: "E",
controller: "myController",
link: function(scope, element, attrs) {
scope.foo = element.text();
},
templateUrl: "myDirTemplate.html"
}
});
模板是:
<div>The value is: {{foo}}</div>
和正在使用的指令如下:
<html>
...
<myDir>Bar</myDir>
...
</html>
链接函数中的元素指的是
<div>The value is: {{foo}}</div>
在模板中。如果我不指定 templateUrl,则 element 指的是
<myDir>Bar</myDir>
在主视图中,这就是我想要的。我希望该指令将“Bar”文本插入到 {{foo}} 中,给出最终结果:
<div>The value is: Bar</div>
但我不知道如何绕过每次选择模板元素的 Angular 。
有什么想法吗?
最佳答案
您需要使用 ngTransclude :
app.directive('myDir', function(){
return {
restrict: "E",
transclude: true,
templateUrl: "myDirTemplate.html",
replace: true
}
});
然后你的外部模板变成类似于:
<div>The value is: <span ng-transclude></span></div>
关于javascript - 在模板中访问 Angular Directive(指令)(元素)的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16115238/