访问模板内的角度指令(元素)的文本 [英] Accessing angular directive (element)'s text inside the template
问题描述
所以我正在关注关于自定义组件的这个 EggHead.io 教程,然后我来了跨越这个问题.声明指令时,例如:
angular.module('myApp', []).directive('myDir', function(){返回 {限制:E",控制器:我的控制器",链接:函数(范围,元素,属性){scope.foo = element.text();},templateUrl: "myDirTemplate.html"}});
和模板是:
值为:{{foo}}
以及使用的指令如下:
...<myDir>Bar</myDir>...</html>
链接函数中的
元素指的是
值为:{{foo}}
在模板中.如果我不指定 templateUrl,那么 element 指的是
Bar
在主视图中,这就是我想要的.我希望指令能够将Bar"文本插入到 {{foo}} 中,给出最终结果:
值为:Bar;
但我不知道如何绕过每次选择模板元素的角度.
有什么想法吗?
您需要使用 ngTransclude:
app.directive('myDir', function(){返回 {限制:E",转置:真实,templateUrl: "myDirTemplate.html",替换:真}});
然后你的外部模板变成类似于:
的值为:
查看此处工作的代码:http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=预览
So I am following this EggHead.io tutorial on custom components, and I came across this problem. When declaring a directive such as:
angular.module('myApp', [])
.directive('myDir', function(){
return {
restrict: "E",
controller: "myController",
link: function(scope, element, attrs) {
scope.foo = element.text();
},
templateUrl: "myDirTemplate.html"
}
});
and the Template being:
<div>The value is: {{foo}}</div>
and the directive being used such as follows:
<html>
...
<myDir>Bar</myDir>
...
</html>
element in the link function refers to the
<div>The value is: {{foo}}</div>
in the template. If I don't specify the templateUrl, then element refers to the
<myDir>Bar</myDir>
in the main view, which is what I want. I was hoping the directive would take the "Bar" text and insert it into the {{foo}}, giving the final result of:
<div>The value is: Bar</div>
But I don't know how to get around angular selecting the template's element every single time.
Any ideas?
You need to use ngTransclude:
app.directive('myDir', function(){
return {
restrict: "E",
transclude: true,
templateUrl: "myDirTemplate.html",
replace: true
}
});
and then your external template becomes something similar to:
<div>The value is: <span ng-transclude></span></div>
View the code working here: http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=preview
这篇关于访问模板内的角度指令(元素)的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!