如何使用指令定义的`replace`? [英] How to use `replace` of directive definition?
问题描述
在本文档中:http://docs.angularjs.org/guide/directive,它说指令有一个 replace
配置:
template - 用 HTML 的内容替换当前元素.替换过程将所有属性/类从旧元素迁移到新元素.有关详细信息,请参阅下面的创建组件部分.
javascript 代码
app.directive('myd1', function(){返回 {模板:'<span>指令模板1</span>',替换:真}});app.directive('myd2', function(){返回 {模板:'<span>指令模板2</span>',替换:假}});
html 代码
应该替换原来的内容<div myd2>不应替换原始内容
但最终页面看起来像:
指令模板1指令模板2
看来 replace
不起作用.我有什么想念的吗?
现场演示:http://plnkr.co/edit/rGIgmjO81X2UxJohL4HM?p=preview一个>
您对 transclude: true
感到困惑,它会附加内部内容.
replace: true
表示指令模板的内容将替换声明指令的元素,在本例中为
http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview
例如没有 replace:true
指令模板1
and with replace:true
正如你在后面的例子中看到的,div 标签确实被替换.
In this document: http://docs.angularjs.org/guide/directive , it says that there is a replace
configuration for directives:
template - replace the current element with the contents of the HTML. The replacement process migrates all of the attributes / classes from the old element to the new one. See the Creating Components section below for more information.
javascript code
app.directive('myd1', function(){
return {
template: '<span>directive template1</span>',
replace: true
}
});
app.directive('myd2', function(){
return {
template: '<span>directive template2</span>',
replace: false
}
});
html code
<div myd1>
original content should be replaced
</div>
<div myd2>
original content should NOT be replaced
</div>
But the final page is looking like:
directive template1
directive template2
It seems the replace
doesn't work. Do I miss anything?
Live demo: http://plnkr.co/edit/rGIgmjO81X2UxJohL4HM?p=preview
You are getting confused with transclude: true
, which would append the inner content.
replace: true
means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1>
tag.
http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview
For example without replace:true
<div myd1><span class="replaced" myd1="">directive template1</span></div>
and with replace:true
<span class="replaced" myd1="">directive template1</span>
As you can see in the latter example, the div tag is indeed replaced.
这篇关于如何使用指令定义的`replace`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!