在angularJS单页aplication使用JavaScript打印一个div [英] Print a div using javascript in angularJS single page aplication

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

问题描述

我在使用angularJS单个页面的Web应用程序。我需要打印某些页面的一个div。
我试过如下:

该页面包含几格(print.html)

 < D​​IV>
  < D​​IV>
    不打印
  < / DIV>
  < D​​IV ID =打印>
    打印该div
  < / DIV>
  <按钮NG点击=printDiv('printableArea');>打印事业部< /按钮>
< / DIV>

该控制器具有以下脚本:

  $ scope.printDiv =功能(divName){
    VAR printContents =的document.getElementById(divName).innerHTML;
    VAR originalContents = document.body.innerHTML;
    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}

这code打印所需的股利,但有一个问题。
声明 document.body.innerHTML = originalContents; 替换整个应用程序的主体,因为它是一个水疗中心。所以,当我刷新页面或者点击打印按钮再次,网页的全部内容被删除。

有人请分享一些想法来解决这个问题。


解决方案

  $ scope.printDiv =功能(divName){
  VAR printContents =的document.getElementById(divName).innerHTML;
  VAR popupWin = window.open('','_blank','宽= 300,高度= 300');
  popupWin.document.open();
  popupWin.document.write('< HTML>< HEAD><链接rel =stylesheet属性类型=文/ CSS的href =style.css文件/>< /头><身体的onload = window.print()>'+ printContents +'< /身体GT;< / 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.

Someone please share some idea to resolve this problem.

解决方案

$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单页aplication使用JavaScript打印一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆