Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile a template without passing scope

Tags:

angularjs

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();    
like image 232
thetallweeks Avatar asked Feb 13 '23 07:02

thetallweeks


1 Answers

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.

like image 52
runTarm Avatar answered Feb 24 '23 18:02

runTarm