编译模板而不传递作用域 [英] Compile a template without passing scope

查看:67
本文介绍了编译模板而不传递作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AngularJS中,有没有一种方法可以使用 scope 或指令将字符串模板转换为标记而无需?

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

我有一项服务,可让我动态创建新的角度应用程序.它为新应用程序构建DOM,然后在元素上运行 angular.boostrap .

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.

当前,DOM是这样创建的:

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.

通常我会使用 $ compile 将字符串模板转换为标记,但是由于我尚未运行 angular.bootstrap ,因此没有 scope ,以便使用 $ compile(template)(scope);

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);

这可行,但是根元素上的所有属性和类都需要单独添加.

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();    

推荐答案

您可以使用 $ interpolate 服务进行字符串替换,如下所示:

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'
});

结果将是这样的:

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

希望这会有所帮助.

这篇关于编译模板而不传递作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆