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

在我的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

点赞