我有一个html页面使用AngularJS,我想打印一个div.有没有一种方式呢? ..或者它只是经典的
JavaScript方式如下:
<script language="javascript" type="text/javascript">
function printDiv(divID) {
//Get the HTML of div
var divelements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divelements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
</script>
如果AngularJS没有任何东西,你可以建议o做这样的方式,而不使用JavaScript函数(例如:doc.getElementById())..接近AngularJS的方法?
谢谢,
解决方法
我已经使用iframe技术创建了一个用于打印div内容的简单指令.这有点黑客,但效果很好.在我看来,没有更好的办法来做到这一点.指令脚本是:
'use strict';
angular.module('yourAppNameHere').directive('printDiv',function () {
return {
restrict: 'A',link: function(scope,element,attrs) {
element.bind('click',function(evt){
evt.preventDefault();
PrintElem(attrs.printDiv);
});
function PrintElem(elem)
{
PrintWithIframe($(elem).html());
}
function PrintWithIframe(data)
{
if ($('iframe#printf').size() == 0) {
$('html').append('<iframe id="printf" name="printf"></iframe>'); // an iFrame is added to the html content,then your div's contents are added to it and the iFrame's content is printed
var mywindow = window.frames["printf"];
mywindow.document.write('<html><head><title></title><style>@page {margin: 25mm 0mm 25mm 5mm}</style>' // Your styles here,I needed the margins set up like this
+ '</head><body><div>'
+ data
+ '</div></body></html>');
$(mywindow.document).ready(function(){
mywindow.print();
setTimeout(function(){
$('iframe#printf').remove();
},2000); // The iFrame is removed 2 seconds after print() is executed,which is enough for me,but you can play around with the value
});
}
return true;
}
}
};
});
在您的模板中,您可以将打印按钮标记为:
<a href="#" print-div=".css-selector-of-the-div-you-want-to-print">Print!</a>
就是这样,它应该工作.
黑客的部分是,iFrame在一定数量的毫秒之后被删除,因为没有跨浏览器的方式来检测打印执行的结束,所以你需要多少时间来运行它.
您可能需要包含jQuery才能正常工作,我不知道如果没有它,我几乎不会工作.我添加了一些内联意见,使事情更清晰.我使用了一些this answer中使用弹出窗口来打印div内容的代码(但在Angular.js之外).也许你会更喜欢这种方法.