在AngularJS中只打印div一次

时间:2018-04-09 08:24:48

标签: javascript html angularjs

我想只打印div一次。其次,它不应该打印。



$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();
} 
&#13;
<div>
  <div>
    Do not print
  </div>
  <div id="printable">
    Print this div
  </div>
  <button ng-click="printDiv('printableArea');">Print Div</button>
</div>
&#13;
&#13;
&#13;

总打印数量为1。然后我想限制它不打印。我怎么能在角度js中这样做。任何人都可以帮助我。

2 个答案:

答案 0 :(得分:1)

您可以在点击

时添加标记
var clicked = false;
$scope.printDiv = function(divName) {
if (clicked) return;
clicked = true;
  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();
} 

答案 1 :(得分:1)

您可以为计数添加变量。您可以动态配置totalCount选项。

var count = {
    totalCount: 1,
    currentCount: 0
};
$scope.printDiv = function(divName) {
   if (count.totalCount == count.currentCount) {
       console.log("Already Printed");
       return;
   }
   count.totalCount += 1;
   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();
}