0

I'm trying to print a div that has been rendered using Angular. I'm using this answer as a starting point https://stackoverflow.com/a/30765875/285190, with the print function being pretty simple

$scope.printIt = function(){
   var table = document.getElementById('printArea').innerHTML;
   var myWindow = $window.open('', '', 'width=800, height=600');
   myWindow.document.write(table);
   myWindow.print();
};

The problem is the innerHTML contains all the items that would exist if the ng-show ng-hide directives hadn't been executed.

Is there a way to get the actual HTML the client is seeing, i.e. after Angular has performed its magic?

Community
  • 1
  • 1
Flexicoder
  • 8,251
  • 4
  • 42
  • 56

1 Answers1

1

Please use $compile service to transform angularized HTML to actual HTML.

Demonstration of $compile https://stackoverflow.com/a/26660649/5317329

$scope.printIt = function () {
    angular.element('#tempHtml').html("");
    var table = document.getElementById('printArea').html();
    var compiledHTML = $compile(table)($scope);
        $timeout(function () {
            angular.element(document.querySelector('#tempHtml')).append(compiledHTML);//Please added <div id="tempHtml"></div> in page/View for temporary storage, Clear the div after print.
            console.log(angular.element('#tempHtml').html());
            var myWindow = $window.open('', '', 'width=800, height=600');
            myWindow.document.write(angular.element('#tempHtml').html());
            myWindow.print();
            angular.element('#tempHtml').html("");//Clearing the html
        }, 300);  // wait for a short while,Until all scope data is loaded If any complex one
};

Hope this will help you

Community
  • 1
  • 1
J-Mean
  • 1,192
  • 1
  • 8
  • 14
  • Thanks, this pointed me in the right direction of `$compile`, but I didn't use it in the end. I ended up having a string template to compile, which also meant I didn't need the `tempHtml` – Flexicoder Dec 21 '16 at 14:52