在没有指令的情况下将模板编译成angular字符串

compiling a template into a string in angular without a directive

本文关键字:编译 angular 字符串 指令 情况下      更新时间:2023-09-26

我正试图将一些html添加到tinyMCE文本区域中(tinyMCE可以在可编辑文本区域中显示html,同时允许用户实时操作它们)。

所以,假设我的模板是:

var template = '<span>hello {{ user.name }}</span>'

我正在努力:

  1. 使用当前控制器的作用域编译模板
  2. 把它串成一个变量(编译后)
  3. 将其连接到tinyMCE编辑器的末尾

我的控制器代码是:

// [...]
var user = {};
user.name = "john";
$scope.user = user;
$templateRequest('<PATH_TO_TEMPLATE>').then(function() {
  var linkingFunc = $compile(template);
  // if I understand correctly, this should replace the user.name with "john"
  var parsedTemplate = linkingFunc($scope);
  console.log(parsedTemplate.prop('outerHTML'));
});
// [...]

parsedTemplate.prop('outerHTML')的输出为:

<span>hello {{ user.name }}</span>

是否只有当我在将它链接到作用域后将其注入DOM时,它才会被渲染?

有没有一种方法可以在javascript中编译它,而不必将其渲染回来?

我正在尝试获得某种var templateWITHOUTVariables,它将使<span>hello john</span> 正常

有什么想法吗?

谢谢!

感谢@FrailWords,我用$timeout解决了这个问题。

所以我的代码看起来是这样的:

var user = {};
user.name = "john";
$scope.user = user;
$templateRequest('<PATH_TO_TEMPLATE>').then(function() {
  var parsedTemplate = $compile(template)($scope); // at this point, the template isn't processed yet
  //timeout in order to get the template processed
  $timeout(function() {
    console.log(parsedTemplate.prop('innerHTML');
  })
});

输出:

<span>hello john</span>

当执行$timeout时,$digest进程已经完成了对parsedTemplate的处理。