0

我正在构建一个使用第三方库的 Angular.js 应用程序。该库要求我传入一个包含 HTML 的字符串。此 HTML 很复杂,需要注入多个值。我想使用 Angular 的内置$compile服务来编译该数据。这是一个例子:

// create the template
var template = "<p>{{ test }}</p>";

// set up the scope
var scope = $rootScope.$new();
scope.test = "hello";

// compile the template
var htmlString = $compile(template)(scope)[0].outerHTML;

当我运行此代码时,我希望htmlString<p>hello</p>,但实际上是<p class="ng-scope ng-binding">{{ test }}</p>. 我了解 Angular 正在设置其绑定,但我想要静态内容。有没有办法实现我想要的行为?

4

1 回答 1

3

正如 sza 所说,由于 $interpolate 函数,解决方案很容易:

var template = 'Hello {{ name }}';
console.log($interpolate(template)({name: 'World'}));

控制台输出为:

Hello World 
于 2013-08-21T01:46:59.057 回答