我正在尝试在页面 html 中插入一个新的。这个 div 应该从 Angular 模板中获取它的内容。
我已经尝试过了,但它不起作用。
var tpl = $compile( '"<div ng-include="template.tpl.html"></div>"' )( scope );
document.body.appendChild(tpl);
tpl 返回空值。
我正在尝试在页面 html 中插入一个新的。这个 div 应该从 Angular 模板中获取它的内容。
我已经尝试过了,但它不起作用。
var tpl = $compile( '"<div ng-include="template.tpl.html"></div>"' )( scope );
document.body.appendChild(tpl);
tpl 返回空值。
不要试图这样做。我知道在处理 jQuery 并使用 Angular 时,我们会感到尝试对所有内容使用字符串以及 appendTo、prepend、replaceWith 的冲动。
指令是你最好的选择,而且你不需要弄脏 jQuery。
app.directive('includeIt', function(){
return {
restrict: 'A',
scope: {template:'=includeIt'},
template: '<div ng-include="template"></div>'
};
});
app.controller('Ctrl', function(){
this.templates = ['template1.tpl.html','template2.tpl.html'];
});
然后你在你的 HTML 中使用指令
<div ng-controller="Ctrl as ctrl">
<div ng-repeat="template in ctrl.templates" include-it="template"></div>
</div>
通过这种方式,您可以自动包含所有“模板”,这些“模板”会自动附加到 DOM,而无需触摸 jQuery。在此处查看实际操作http://plnkr.co/edit/WFEcB1QJlD9D98rC57J9?p=preview