javascript - AngularJS - 如何从 $compile 获取处理后的 HTML 输出?

标签 javascript angularjs templates compilation

我有以下函数,它获取自定义 HTML 模板并将一些值传递到范围中以生成“报告表”。因为模板对用户不可见,但处理后的输出直接发送到另一个函数,因此我使用了 $compile 函数。

似乎传递到 $scope 的值已正确处理,但我无法获得纯 HTML 结果。

我尝试通过这种方式做到这一点:

var templateUrl = $sce.getTrustedResourceUrl('report.html');

          $templateRequest(templateUrl).then(function(template) {
            $scope.rows = reportData;
            var compTest = $compile(template)($scope);
            console.log(compTest); //IT RETURNS A LOT OF VALUES BUT NOT HTML OUPUT OF THE PROCESSED TEMPLATE
          }, function() {
            // An error has occurred
          });

非常感谢您的建议。

结果如下:

enter image description here

HTML 内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Report</title>
</head>
<body>
<table>
  <thead>
  <td>
    &nbsp;
  </td>
  <td>
    Breakfast
  </td>
  <td>
    Lunch
  </td>
  <td>
    Dinner
  </td>
  <td>
    Snack
  </td>
  </thead>
  <tbody>
  <tr ng-repeat="row in rows">
    <td>TEST</td>
    <td>40</td>
    <td>20</td>
    <td>30</td>
    <td>10</td>
  </tr>
  </tbody>
</table>
</body>
</html>

最佳答案

$compile 将返回一个函数,然后由 scope 执行该函数,而该函数又将返回一个 jQlite 包装的 DOM 对象。所以你可以使用outerHTML来获取模板字符串

您可以使用$interpolate,如下所示

演示

angular.module('myApp', []);
angular
  .module('myApp')
  .controller('MyController', MyController);

function MyController($scope, $compile, $interpolate) {
  var template = '<a ng-click="handler()">click handler</a>';
  this.tmpl = $compile(template)($scope)[0].outerHTML;
  this.tmplInt = $interpolate(template)($scope);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyController as MC">
    <p><b>using $compile along with outerHTML </b>{{MC.tmpl}}</p>
    <p><b>using $interpolate </b>{{MC.tmplInt}}</p>
  </div>
</div>

关于javascript - AngularJS - 如何从 $compile 获取处理后的 HTML 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256704/

相关文章:

javascript - 在测试使用 Promise 的 Node 模块时如何断言?

javascript - 将 Controller 中的参数范围函数分配给指令中的 var

javascript - 如何在 Angular $resource 中传递动态参数

c++ - 这段代码会抛出访问冲突异常吗

javascript - AngularJS $scope 对象是什么类型的设计模式?

javascript - 通过 HTTP 在 javascript 中发送二进制数据

angularjs - 根据下拉菜单 1 的选择填充下拉菜单 2

c++ - 如何使用带有重载的enable_if

c++ - 在 SWIG 中包装 C++ 结构模板

javascript - 正则表达式仅在 "asdf:adsf"中查找冒号,但在 "asdf: adsf"中查找不到