gpt4 book ai didi

angularjs - 使用 nginclude 时避免使用额外的 DOM 节点

转载 作者:行者123 更新时间:2023-12-03 03:44:36 27 4
gpt4 key购买 nike

当我从纯 HTML 演示构建 Angular 应用程序时,我正在努力思考如何让 ng-include 不使用额外的 DOM 元素。我正在使用相当纤薄的 HTML 和完全开发的、紧密 DOM 耦合的 CSS(由 SASS 构建),并且我想不惜一切代价避免重构。

这是实际的代码:

<div id="wrapper">
<header
ng-controller="HeaderController"
data-ng-class="headerType"
data-ng-include="'/templates/base/header.html'">
</header>
<section
ng-controller="SubheaderController"
data-ng-class="subheaderClass"
ng-repeat="subheader in subheaders"
data-ng-include="'/templates/base/subheader.html'">
</section>
<div
class="main"
data-ng-class="mainClass"
data-ng-view>
</div>
</div>

我需要

作为一个重复元素,但有自己的逻辑和不同的内容。内容和重复次数都取决于业务逻辑。正如您所看到的,将 ng-controller 和 ng-repeat 放在
元素上将不起作用。然而,插入一个新的 DOM 节点是我试图避免的。

我错过了什么?这是最佳实践还是有更好的方法?

<小时/>

编辑:只是为了按照评论中的要求进行澄清,我尝试生成的最终 HTML 是:

<div id="wrapper">
<header>...</header>
<section class="submenuX">
some content from controller A and template B (e.g. <ul>...</ul>)
</section>
<section class="submenuY">
different content from same controller A and template B (e.g. <div>...</div>)
</section>
<section class="submenuZ">
... (number of repetitions is defined in controller A e.g. through some service)
</section>

<div>...</div>
</div>

我想使用相同的模板 B (subheader.html) 的原因是为了代码整洁。我认为 subheader.html 有某种 ng-switch 以便返回动态内容。

但基本上,根本问题是:有没有一种方法可以透明地包含模板的内容,而不使用 DOM 节点?

<小时/>

EDIT2:解决方案需要可重用。 =)

最佳答案

其他一些答案建议replace:true,但请记住模板中的replace:truemarked for deprecation .

相反,在 an answer to a similar question ,我们找到了一个替代方案:它允许您编写:

<div ng-include src="dynamicTemplatePath" include-replace></div>

自定义指令:

app.directive('includeReplace', function () {
return {
require: 'ngInclude',
restrict: 'A', /* optional */
link: function (scope, el, attrs) {
el.replaceWith(el.children());
}
};
});

(从其他答案中剪切粘贴)

关于angularjs - 使用 nginclude 时避免使用额外的 DOM 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17589358/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com