AngularJS中打印Div功能异常问题求助
解决AngularJS打印时文本框内容不显示的问题
嘿,我来帮你搞定这个问题!你遇到的核心问题是:AngularJS的双向绑定机制和你直接复制DOM innerHTML的方式不兼容。
问题根源
你现在的代码是直接通过document.getElementById(printSectionId).innerHTML抓取页面的HTML结构,但Angular的ng-model是把输入的数据存在$scope里,并没有同步更新DOM元素的value属性。当你把这段HTML放到新窗口时,新窗口没有Angular的运行环境,自然没办法把$scope里的数值渲染到文本框里,所以打印出来的就是空框。
两种修复方案,任你选
方案1:快速修复——手动同步DOM值
在抓取innerHTML之前,先把$scope里的输入值手动赋值给对应的文本框的value属性,这样抓取到的HTML就会包含输入的内容:
$scope.printToCart = function(printSectionId) { // 先把$scope里的数据同步到DOM的value属性 document.querySelector('input[ng-model="firstName"]').value = $scope.firstName; document.querySelector('input[ng-model="lastName"]').value = $scope.lastName; var innerContents = document.getElementById(printSectionId).innerHTML; var popupWinindow = window.open('', '_blank', 'width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no'); popupWinindow.document.open(); popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>'); popupWinindow.document.close(); }
方案2:更优雅的方式——用专门的打印模板
这更符合Angular的设计理念,我们创建一个隐藏的打印专用模板,直接用插值表达式渲染$scope里的数据,不需要操作DOM:
首先在HTML里添加隐藏的打印模板:
<!-- 这个模板平时隐藏,只在打印时使用 --> <div id="printTemplate" style="display: none;"> <h1>AngularJS Print html templates</h1> <form novalidate> First Name: <input type="text" value="{{firstName}}" class="tb8"> <br><br> Last Name: <input type="text" value="{{lastName}}" class="tb8"> <br><br> </form> </div>
然后修改打印函数,抓取这个模板的内容:
$scope.printToCart = function() { var innerContents = document.getElementById('printTemplate').innerHTML; var popupWinindow = window.open('', '_blank', 'width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no'); popupWinindow.document.open(); popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>'); popupWinindow.document.close(); }
最后修改打印按钮的点击事件,不需要传ID了:
<button ng-click="printToCart()" class="button">Print</button>
总结
方案1适合快速修复现有代码,方案2更符合Angular的数据驱动思想,也更容易维护。两种方法都能解决你打印时文本框为空的问题~
内容的提问来源于stack exchange,提问作者sathish kumar
相关产品推荐
相关产品推荐

