[英]AngularJs transclude not working in Directive template or templateURL
I have written a custom directive like so, notice I have commented out the template URL that contains the same HTML structure and the template property: 我已经这样写了一个自定义指令,请注意,我已经注释掉了包含相同HTML结构和template属性的模板URL:
.directive('sillyDirective', function ( ) {
'use strict';
return {
restrict: 'A',
replace: false,
transclude: true,
template: '<h2>Welcome to my site</h2>',
//templateUrl: '/views/hello.html' ,
link: function (scope, element, attrs) {
element.bind('click', function (){
alert('you click me! I am clicked');
});
};
});
In my HTML view I have the following... 在我的HTML视图中,我有以下内容...
<div data-silly-directive>
<div><img src="logo.jpg></div>
<div><h1>My First Website</h1></div>
</div>
The problem is the content of the directive, eg: 问题是指令的内容,例如:
<div><img src="logo.jpg></div>
<div><h1>My First Website</h1></div>
is being overwritten with the template content even thought I have set transclude
to true and replace
to false? 是否以模板内容覆盖,甚至以为我已将
transclude
设置为true并replace
为false? What am I doing wrong here? 我在这里做错了什么?
Your template must contain an element with an ng-transclude attribute. 您的模板必须包含具有ng-transclude属性的元素。 That's where the body will be "pasted" by angular.
那就是身体将被角度“粘贴”的地方。
See https://docs.angularjs.org/api/ng/directive/ngTransclude 参见https://docs.angularjs.org/api/ng/directive/ngTransclude
you need to specify ng-transclude in the template of your directive, this will let angular know where to insert the content of the markup. 您需要在指令模板中指定ng-transclude,这将使angular知道在哪里插入标记内容。
app.directive("foo", function() {
return {
transclude: true,
template: "<div>the template</div><div ng-transclude></div>"
};
})
html: 的HTML:
<div foo>
Some Content Here
</div>
result: 结果:
<div foo>
<div>the template</div>
<div ng-transclude>Some Content Here</div>
</div>
source: https://www.accelebrate.com/blog/angularjs-transclusion-part-1/ 来源: https : //www.accelebrate.com/blog/angularjs-transclusion-part-1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.