Compile a template without going through an area

Question

In AngularJS, is there a way to convert a string template into markup without using scopeor directives?

Description

I have a service that allows me to dynamically create new angular applications. It creates a DOM for a new application, then runs angular.boostrapon the element.

Currently, the DOM is created as follows:

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

There are many attributes , classes , children , etc., so creating markup this way is not ideal. Better to use a template.

I usually used $compileto convert a string template to markup, but since I haven't run it yet angular.bootstrap, for$compile(template)(scope);

no scope

What i tried

Create a div, then replace innerHTML with a template string

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

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

Delete region after template compilation

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

var scope = $rootScope.$new();
var element = $compile(template)(scope);
scope.$destroy();    
+4
source share
1 answer

You can use the $interpolateline substitution service as follows:

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 will be like this:

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

Hope this helps.

+7
source

All Articles