【问题标题】:Is it possible to $compile with angular HTML document是否可以使用角度 HTML 文档进行 $compile
【发布时间】:2015-04-04 00:13:25
【问题描述】:

是否可以 $compile HTML 文档,而不是像 $compile 期望的元素?

我要解决的问题:我在外部 .html 文件中有可打印的表单,我想包含这一行:<link rel="stylesheet" type="text/css" href="styles.css">

现在我不能这样做,因为 $compile 期望 element 参数,这是 DOM 元素并且不能包含(或简单地忽略到样式表的链接)。

我有的模板:

<div>
    <span ng-bind="model.tasks.count"></span>
</div>

我想要的模板(我的主要目标 - 将样式提取到单独的文件中):

<html>
  <head>
    <link href="/app/style.css" rel="stylesheet">
  </head>

  <body>
    <div>
        <span ng-bind="model.tasks.count"></span>
    </div>
  </body>
</html>

我的代码示例:

return $q.all([ getTemplate(), getScope() ]).then(
    function(msg) {
        var element = angular.element(msg[0]); // Now it's DOM element
        $compile(element)(msg[1]); // If i pass HTML document, element goes undefined
        openWindow(element);
    });

和打开窗口:

function openWindow(element) {
    $timeout(function () {
        var html = element.html();

        var _w = window.open();
        _w.document.body.innerHTML = html; // Here i'd like to write complete HTML doc
        _w.print();
    });
}

【问题讨论】:

    标签: javascript jquery html css angularjs


    【解决方案1】:

    是否可以 $compile HTML 文档,而不是像 $compile 这样的元素 期待?

    这并不正确,$compile 期望任何内容,您可以将整个 html 作为字符串传递给angular.element$compile。但答案仍然是否定的,$compile 在后台使用 jqLit​​e:

      if (!($compileNodes instanceof jqLite)) {
        // jquery always rewraps, whereas we need to preserve the original selector so that we can
        // modify it.
        $compileNodes = jqLite($compileNodes);
      }
      // We can not compile top level text elements since text nodes can be merged and we will
      // not be able to attach scope data to them, so we will wrap them in <span>
      forEach($compileNodes, function(node, index) {
        if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
          $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
        }
      });
    

    jqLit​​e 会将 html 文档以与 jQuery() 相同的方式处理 - 作为来自 &lt;head&gt;&lt;body 的顶级元素的集合。当然,$compile 并非用于编译整个文档。

    如果您希望在模板中添加样式,则可以使用 &lt;style type="text/css"&gt;@import url("...")&lt;/style&gt;

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2010-09-13
      • 2022-08-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      相关资源
      最近更新 更多