Javascript AngularJS - 为什么不使用 templateUrl 属性替换:true 工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11426114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS - Why doesn't replace: true work with templateUrl property?
提问by dnc253
I have a pretty simple directive that I want to load the template from a separate HTML file. I want the HTML to replace the directive and so I add the replace: true
property to the directive. However when I do this, the template doesn't get included at all.
我有一个非常简单的指令,我想从单独的 HTML 文件加载模板。我希望 HTML 替换指令,因此我将replace: true
属性添加到指令中。但是,当我这样做时,模板根本不包含在内。
I've created a jsFiddlewhere you can see this. If you use Firebug or something to inspect the DOM, you can see that when it's using just the template
property it does replace the element. If you take off the replace: true
you can see the HTML at the templateUrl
getting appended to the foo element. However, as soon as I add the replace: true
with the templateUrl
, all I see is <foo></foo>
in the DOM.
我创建了一个jsFiddle,您可以在其中看到这一点。如果您使用 Firebug 或其他东西来检查 DOM,您会发现当它只使用template
属性时,它确实替换了元素。如果你去掉 ,replace: true
你可以看到templateUrl
附加到 foo 元素的 HTML 。但是,只要我添加了replace: true
与templateUrl
所有我看到的是<foo></foo>
在DOM。
Is there some reason you just can't use these two properties together? I'm far from an expert with javascript, so any information about what is going on here would be greatly appreciated.
有什么原因不能一起使用这两个属性吗?我远非 javascript 专家,因此将不胜感激任何有关此处发生的事情的信息。
回答by Gloopy
Make sure the contents of your html in the templateUrl
has exactly one root element. This is not an issue when replace: false
but becomes an issue when replace: true
and you will see this Console error (with FireBug):
确保 html 中的内容templateUrl
只有一个根元素。replace: false
当replace: true
您看到此控制台错误(使用 FireBug)时,这不是问题,但会成为问题:
Error: Template must have exactly one root element.
Here is a jsFiddle of it not working(with two root elements) and another with it working.
回答by Dan Doyon
Good question. If I'm not mistaken, you want to use "transclude"
好问题。如果我没记错的话,你想使用“transclude”
http://jsfiddle.net/dandoyon/AsVp8/1/
http://jsfiddle.net/dandoyon/AsVp8/1/
Transclude allows you to blend your template with what is in the HTML. You may want to give the doc another glance and look for this option.
Transclude 允许您将模板与 HTML 中的内容混合。您可能想再看一眼文档并查找此选项。
cheers!
干杯!