我想要一种创建方法来打印网页的一部分,因此我创建了一个名为 printDiv 的函数,它接受 div ID 并弹出一个新窗口并打印该 div 的innerHTML。然而,当将innerHTML与Angular一起使用时,它似乎会忽略Angular ng-show语句并打印所有内容。
在 Angular ng-show 处理之后,是否有一种简单的方法来获取正在呈现给用户的真正的 innerHTML?
我创建了一个带有打印按钮的基本版本,该按钮调用 plunker here 中的 printDiv 函数。 。
这是 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();
}
});
最佳答案
尝试使用 ng-if 而不是 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>
找出 ng-show 和 ng-if 之间的区别 here
关于javascript - innerHTML 忽略 Angular ng-show,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37416268/