绑定一个值并使用 AngularJS 打印外部 HTML 而无需加载到浏览器

Bind a value and Print the External HTML using AngularJS without loading into the browser

我有 2 个 HTML 视图,一个用于应用目的,另一个用于打印目的。只需考虑两个文件名 Application.htmlPrintForm.html

示例 HTML Application.html

的脚本

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
  
Full Name: {{firstName + " " + lastName}}<br>
<br> Click here to <a href="#">Print</a>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});
</script>

</body>
</html>

示例 HTML PrintForm.html

的脚本

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<h1 class="visible">My First Name is {{  }}</h1>
<h1 class="visible">My Last Name is {{  }}</h1>

<p>The Value fetched from Application.html</p>

</body>
</html>

如果我单击来自 Application.html 的打印超链接,我需要使用来自 app.controller $scope

的数据打印 PrintForm.html
$scope.firstName = "John";
$scope.lastName = "Doe";

预期的输出屏幕是

我不需要将打印内容加载到浏览器中,它直接触发打印机对话框打印,打印超链接被点击后。

我在点击 Application.html 中的打印超链接后的预期操作应该是

Note: Don't use iFrame or any other inner View for the PrintForm.html

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<div>
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
  
Full Name: {{firstName + " " + lastName}}<br>
<br> Click here to <a href="#" ng-click="printDiv('PrintID')">Print</a>

</div>

<div id="PrintID" style="visibility: collapse;">
<h1 class="visible">My First Name is {{ firstName }}</h1>
<h1 class="visible">My Last Name is {{ lastName }}</h1>

<p>The Value fetched from Application.html</p>
</div>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
 
 

$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><title>Print<title></head><body onload="window.print()">' + printContents + '</body></html>');
  popupWin.document.close();
} 
 
});
</script>

</body>
</html>

下面的源码完全可以满足您的要求。