0

I want to a create way to print a section of a webpage, so I created a function called printDiv that takes a div ID and pops up a new window and prints that div's innerHTML. This works, however, the when using innerHTML with Angular it seems to ignore the Angular ng-show statements and prints everything.

Is there an easy way to get the true innerHTML that is being rendered to the user, after the Angular ng-show processing?

I've created a basic version with a print button that calls the printDiv function in this plunker here.

Here's the code that's in the plunker:

<button class="btn" ng-click="printDiv('MainPrintPane')">Print</button>
<div id="MainPrintPane">
  <div ng-show="showDiv1">Show if showDiv1 is true</div>
  <div ng-show="showDiv2">Show if showDiv2 is true</div>
  <div ng-show="showDiv3">Show if showDiv3 is true</div>
</div>


app.controller('MainCtrl', function($scope) {
  $scope.showDiv1 = true;
  $scope.showDiv2 = false;
  $scope.showDiv3 = false;

  $scope.printDiv = function(divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var popupWin = window.open('', '_blank', 'width=600,height=500,resizable,scrollbars=1');
    popupWin.document.open();
    popupWin.document.write('<html><head><title>Print</title></head><body onload="window.print()">' + printContents + '</body></html>');
    popupWin.document.close();
  }
});
mkimmet
  • 749
  • 3
  • 15
  • 27

1 Answers1

1

try use ng-if instead of ng-show

<button class="btn" ng-click="printDiv('MainPrintPane')">Print</button>
   <div id="MainPrintPane">
   <div ng-if="showDiv1">Show if showDiv1 is true</div>
   <div ng-if="showDiv2">Show if showDiv2 is true</div>
   <div ng-if="showDiv3">Show if showDiv3 is true</div>
</div>

find the difference between ng-show and ng-if here

Community
  • 1
  • 1
Yousef
  • 81
  • 7