AngularJS - 为什么不使用 templateUrl 属性替换:true 工作? [英] AngularJS - Why doesn't replace: true work with templateUrl property?

查看:25
本文介绍了AngularJS - 为什么不使用 templateUrl 属性替换:true 工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的指令,我想从单独的 HTML 文件加载模板.我希望 HTML 替换指令,因此我将 replace: true 属性添加到指令中.但是,当我这样做时,模板根本不包含在内.

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.

我创建了一个 jsFiddle 在这里你可以看到这个.如果您使用 Firebug 或其他工具来检查 DOM,您会发现当它仅使用 template 属性时,它确实替换了元素.如果去掉 replace: true,您可以看到 templateUrl 处的 HTML 被附加到 foo 元素.但是,一旦我将 replace: true 添加到 templateUrl,我看到的只是 <foo></foo>DOM.

I've created a jsFiddle where 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.

是否有某些原因您不能同时使用这两个属性?我远非 JavaScript 专家,因此非常感谢您提供有关这里发生的事情的任何信息.

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.

推荐答案

确保 templateUrl 中的 html 内容只有一个根元素.这在 replace: false 时不是问题,但在 replace: true 时会成为问题,您将看到此控制台错误(使用 FireBug):

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):

Error: Template must have exactly one root element.

这是一个 jsFiddle 不工作(有两个根元素),另一个有它工作.

Here is a jsFiddle of it not working (with two root elements) and another with it working.

这篇关于AngularJS - 为什么不使用 templateUrl 属性替换:true 工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆