javascript - 以编程方式将 Angular 模板编译为 HTML 字符串

标签 javascript angularjs

在我的 Angular 1.5.11 应用程序中,我尝试以编程方式编译模板并将结果作为 HTML 字符串获取。模板内容为

<div ng-if="foo">
  <div>foo is {{foo}}, bar is {{bar}}</div>
</div> 

我尝试将其编译为 HTML 字符串:

app.controller('MainCtrl', function($scope, $rootScope, $compile) {

  function compileHtmlTemplate (templateContent, model) {
    var templateScope = $rootScope.$new(true);
    angular.extend(templateScope, model);

    return $compile(templateContent)(templateScope);
  }

  var templateContent = $('#template').html();
  var model = {foo: 'fooValue', bar: 'barValue'};
  var compiledHtml = compileHtmlTemplate(templateContent, model);
  var htmlAsString = $('<div></div>').html(compiledHtml).html();

  $scope.result = htmlAsString;
});

但是,正如您在此 Plunker example 中看到的那样, 它不起作用。我需要编译模板而不只是对其进行插值,因为它包含一个 ng-if 指令。

最佳答案

Angular 的摘要循环需要先完成,然后您才能访问该值。您可以通过使用 $timeout 来实现。

我使用 $templateCache 来检索模板,因为这是官方方式,但这只是个人喜好。

var app = angular.module('plunker', ['ngSanitize']);

app.controller('MainCtrl', function($scope, $rootScope, $compile, $timeout, $templateCache) {

  function compileHtmlTemplate (templateContent, model) {
    var templateScope = $rootScope.$new(true);
    angular.extend(templateScope, model);

    var compiled = $compile(templateContent)(templateScope);

    var parent = $("<div>").html(compiled);

    console.log("Won't work! Digest hasn't finished:", parent[0].innerHTML);

    $timeout(function(){ // must wait till Angular has finished digest
      console.log('Will work, digest has now completed:', parent[0].innerHTML);

      $scope.result = parent[0].innerHTML;
    }, 0);
  }

  // either do something with the compiled value within the $timeout, or watch for it
  $scope.$watch('result', function(newValue, oldValue) {
      if (newValue !== undefined) {
        console.log("Do something in the $timeout or here... " + newValue);
      }
  });

  // you can access the template via the template cache if you wanted
  var templateContent = $templateCache.get('template');
  var model = {foo: 'fooValue', bar: 'barValue'};
  var compiledHtml = compileHtmlTemplate(templateContent, model);
});

更新的 Plunker:https://plnkr.co/edit/ajC3Iqkxpi6O9gfieHeR?p=preview

关于javascript - 以编程方式将 Angular 模板编译为 HTML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43276380/

相关文章:

javascript - 使用 Web Audio API 播放录制的音频 block

firefox - Angular xhr 请求在 Firefox 中导致重定向警告

angularjs - 我可以自定义我的 AngularJS 应用程序来显示本地时间吗?

javascript - 带有复选框的 Gridview

javascript - 具有嵌套对象和 st-search 的 AngularJS 智能表奇怪行为

javascript - 使用 ES6 导出样式表

javascript - 具有angularJS应用程序的 Angular Material

javascript - jquery 执行函数列表

javascript - 通过 AngularJS 中的 Controller 将结果从一个工厂/服务 ajax 方法传递到另一个方法

angularjs - 如何将大型 AngularJS 项目拆分为模块