2015-04-03 54 views
1

是否可以$编译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); 
    }); 

and openWindow:

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(); 
    }); 
} 

回答

0

是否可以$编译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() - 作为顶级元素从<head><body的集合。当然,$compile并非用于编译整个文档。

如果您在模板中使用样式,则可以使用<style type="text/css">@import url("...")</style>