Compile a template without passing scope

删除回忆录丶 提交于 2021-01-27 07:50:21

问题


Question

In AngularJS, is there a way to convert a string template into markup without using scope or a directive?

Explanation

I have a service which allows me to create new angular apps dynamically. It builds up the DOM for the new app, then runs angular.boostrap on the element.

Currently, the DOM is created like this:

var element = document.createElement('div');
element.setAttribute('app', '');
element.setAttribute('size', 'small');
...
element.className = 'app layout--relative';

There are many attributes, classes, child elements, etc, so creating the markup in this way is not ideal. It would be better to use a template.

Normally I would use $compile to convert a string template into markup, but because I have not run angular.bootstrap yet, there is no scope in order to use $compile(template)(scope);

What I have tried

Create a div, then replace the innerHTML with the template string

This works, but all of the attributes and classes on the root element need to be added separately.

var element = document.createElement('div');
element.innerHTML = template;

Remove scope after the template has compiled

This works, but I would prefer to avoid scope altogether:

var scope = $rootScope.$new();
var element = $compile(template)(scope);
scope.$destroy();    

回答1:


You could use the $interpolate service for string substitution like this:

var template = '<div app size="{{size}}" class="{{className}}">' +
                 '<span>Hello {{name}}!</span>' +
               '</div>';

$interpolate(template)({
  size: 'small',
  className: 'app layout--relative',
  name: 'World'
});

and the result would be like this:

<div app size="small" class="app layout--relative">
  <span>Hello World!</span>
</div>

Hope this helps.



来源:https://stackoverflow.com/questions/25212851/compile-a-template-without-passing-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!