
本文介绍了用模板替换 ng-include 节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对 Angular 有点陌生.是否可以用包含模板的内容替换 ng-include 节点?例如,使用:
<script type="text/ng-template" id="test.html"><p>测试</p><div ng-include src="'test.html'"></div>
生成的html为:
<script type="text/ng-template" id="test.html"><p>测试</p><div ng-include src="'test.html'"><span class="ng-scope"></span><p>测试</p><span class="ng-scope"></span>
但我想要的是:
<script type="text/ng-template" id="test.html"><p>测试</p><p>测试</p>
解决方案
我遇到了同样的问题,但仍然希望 ng-include 的特性包含一个动态模板.我正在构建一个动态 Bootstrap 工具栏,我需要更清晰的标记才能正确应用 CSS 样式.
以下是我为感兴趣的人提出的解决方案:
HTML:
<div ng-include src="dynamicTemplatePath" include-replace></div>
自定义指令:
app.directive('includeReplace', function () {返回 {要求:'ngInclude',限制:'A',/* 可选 */链接:功能(范围,EL,属性){el.replaceWith(el.children());}};});
如果在上面的示例中使用了此解决方案,将 scope.dynamicTemplatePath 设置为 'test.html' 将产生所需的标记.
Kinda new to angular. Is it possible to replace the ng-include node with the contents of the included template? For example, with:
<div ng-app>
<script type="text/ng-template" id="test.html">
<p>Test</p>
</script>
<div ng-include src="'test.html'"></div>
</div>
The generated html is:
<div ng-app>
<script type="text/ng-template" id="test.html">
<p>Test</p>
</script>
<div ng-include src="'test.html'">
<span class="ng-scope"> </span>
<p>Test</p>
<span class="ng-scope"> </span>
</div>
</div>
But what I want is:
<div ng-app>
<script type="text/ng-template" id="test.html">
<p>Test</p>
</script>
<p>Test</p>
</div>
解决方案
I had this same issue and still wanted the features of ng-include to include a dynamic template. I was building a dynamic Bootstrap toolbar and I needed the cleaner markup for the CSS styles to be applied properly.
Here is the solution that I came up with for those who are interested:
HTML:
<div ng-include src="dynamicTemplatePath" include-replace></div>
Custom Directive:
app.directive('includeReplace', function () {
return {
require: 'ngInclude',
restrict: 'A', /* optional */
link: function (scope, el, attrs) {
el.replaceWith(el.children());
}
};
});
If this solution were used in the example above, setting scope.dynamicTemplatePath to 'test.html' would result in the desired markup.
这篇关于用模板替换 ng-include 节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!