访问角指令(元素)的模板内的文本
所以我下面的上的自定义组件此EggHead.io教程,我碰到这个问题来了。当声明指令如:
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"
}
});
和模板的存在:
<div>The value is: {{foo}}</div>
和正在使用的指令,例如,如下所示:
and the directive being used such as follows:
<html>
...
<myDir>Bar</myDir>
...
</html>
的元素的在链接功能的指
<div>The value is: {{foo}}</div>
在模板中。如果我不指定的 templateUrl 的,然后的元素的指
<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.
任何想法?
您需要使用 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>
查看code在这里工作:http://plnkr.co/edit/EuT5UlgyxgM8d54pTpOr?p=$p$pview