在 angularJS 单页应用程序中使用 javascript 打印一个 div [英] Print a div using javascript in angularJS single page application

查看:24
本文介绍了在 angularJS 单页应用程序中使用 javascript 打印一个 div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 angularJS 的单页 Web 应用程序.我需要打印某个页面的 div.我尝试了以下方法:

页面包含很少的 div (print.html)

<div>不打印

<div id="可打印">打印这个div

<button ng-click="printDiv('printableArea');">Print Div</button>

控制器有以下脚本:

$scope.printDiv = function(divName) {var printContents = document.getElementById(divName).innerHTML;var originalContents = document.body.innerHTML;document.body.innerHTML = 打印内容;窗口.打印();document.body.innerHTML = originalContents;}

此代码打印了所需的 div,但存在问题.语句 document.body.innerHTML = originalContents; 替换了整个应用程序的主体,因为它是一个 SPA.所以当我刷新页面或再次点击打印按钮时,页面的整个内容都被删除了.

解决方案

$scope.printDiv = function(divName) {var printContents = document.getElementById(divName).innerHTML;var popupWin = window.open('', '_blank', 'width=300,height=300');popupWin.document.open();popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css"/></head><body onload="window.print()">' + printContents + '</body></html>');popupWin.document.close();}

I have a single page web application using angularJS. I need to print a div of certain page. I tried the following:

The page contains few div (print.html)

<div>
  <div>
    Do not print
  </div>
  <div id="printable">
    Print this div
  </div>
  <button ng-click="printDiv('printableArea');">Print Div</button>
</div>

The controller has following script:

$scope.printDiv = function(divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;        
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}

This code prints the desired div but there is a problem. the statement document.body.innerHTML = originalContents; replaces the body of the whole application since it is a SPA. So when I refresh the page or click on print button again, the whole content of the page is erased.

解决方案

$scope.printDiv = function(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var popupWin = window.open('', '_blank', 'width=300,height=300');
  popupWin.document.open();
  popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
  popupWin.document.close();
} 

这篇关于在 angularJS 单页应用程序中使用 javascript 打印一个 div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆