如何编译Angular模板并使用appendChild将其插入DOM?

时间:2014-03-28 16:35:58

标签: angularjs angularjs-compile

我正在尝试在页面html中插入一个新内容。这个div应该从Angular模板中获取它的内容。

我已经尝试了这个并且它不起作用。

var tpl = $compile( '"<div ng-include="template.tpl.html"></div>"' )( scope );
document.body.appendChild(tpl); 

tpl返回null。

1 个答案:

答案 0 :(得分:2)

不要试图这样做。我知道在处理jQuery并加入Angular时,我们会感到有尝试使用字符串的冲动,并且appendTo,prepend,replaceWith。

指令是你最好的选择,你不需要让你的手jQuery-dirty。

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

相关问题