$ window.print(),不会在角度js中打印更新的模型数据

vij*_*and 5 javascript angularjs

我有一个表格,其中包含一些要在html中查看的数据.当我点击打印时,我需要从db获取所有数据并打印它.当我点击打印时,我正在获取数据并填充模型数据,只更新模型并打印显示旧数据.在下面的代码中,当我点击打印时,新项目不会添加到项目中.

http://jsfiddle.net/vijaivp/Y3BJa/306/

HTML

<div ng-app>
    <div class="hidden-print" ng-controller="PrintCtrl">
        <br />
        <div id="overallPrint" class='visible-print' style="float:left;     margin-right:50px;">
            <h4>Overall Report</h4>

            <table border="1">
                <thead>
                    <tr>
                        <td>Name</td>
                        <td>Price</td>
                        <td>Quantity</td> 
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="item in items">
                        <td>{{item.Name}}</td>
                        <td>{{item.Price}}</td>
                        <td>{{item.Quantity}}</td>                       
                    </tr>
                </tbody>
            </table>

            <br>
            <input type="button" value="Print Overall" ng-click='printOverallReport()' />
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

JS

function PrintCtrl($scope, $window, $q)  {
    $scope.items = [

        {Name: "Soap", Price: "25", Quantity: "10"},
        {Name: "Shaving cream", Price: "50", Quantity: "15"}
    ];

    $scope.newitems = [
        {Name: "Shampoo", Price: "100", Quantity: "5"}
    ];

    $scope.printOverallReport = function () {
        $scope.items.push($scope.newitems[0]);
        $window.print();
    };
}
Run Code Online (Sandbox Code Playgroud)

Omr*_*ron 6

使用Angular $timeout服务的超时将修复它:

function PrintCtrl($scope, $window, $q, $timeout)  {
        $scope.items = [

            {Name: "Soap", Price: "25", Quantity: "10"},
            {Name: "Shaving cream", Price: "50", Quantity: "15"}
        ];

        $scope.newitems = [
            {Name: "Shampoo", Price: "100", Quantity: "5"}
        ];

    $scope.printOverallReport = function () {
        $scope.items = $scope.newitems;
        console.log($scope.items.length);
        $timeout($window.print, 0);
        console.log($scope.items.length);
      };

}
Run Code Online (Sandbox Code Playgroud)

小提琴

有关原因的全面解释,请参阅DVK的答案(第二篇):为什么setTimeout(fn,0)有时有用?

TL:DR;

当您调用时$window.print(),旧的HTML仍然存在,因为浏览器尚未呈现它.它正在等待完成javascript函数运行.设置$ timeout 0将在执行队列结束时对打印进行排队,并保证在HTML呈现后发生.(我仍强烈建议阅读他的回答)