如何计算每页ng-repeat的值总和?

时间:2016-03-13 09:52:34

标签: javascript angularjs pagination

问题

例如:totalImprCount在所有页面上返回相同的值,因为它仅从最后一页返回总和。

预期结果

我想为每个页面显示以下内容的正确总和:

totalImprCount, totalClickCount, totalMediaSpend, and totalAdvertiserSpend

使用分页

Angular Utils分页: https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination

在控制器中

$scope.pageSize = 20;

// campaignstats is an array of objects

function sum(campaignstats){
            var imprCount, clickCount, mediaSpend, advertiserSpend;
            imprCount = clickCount = mediaSpend = advertiserSpend = 0;
            var statsPerPage = $scope.pageSize;
            if (campaignstats) {
                for (var stats = 0; stats < campaignstats.length; stats++){
                    imprCount += parseInt(campaignstats[stats].impr);
                    clickCount += parseInt(campaignstats[stats].click);
                    mediaSpend += parseFloat(campaignstats[stats].media_spend);
                    advertiserSpend += parseFloat(campaignstats[stats].advertiser_spend);
                    $scope.calcCtr = clickCount/imprCount * 100;
                    if (stats == statsPerPage - 1) {
                        $scope.totalImprCount = imprCount;
                        $scope.totalClickCount = clickCount;
                        $scope.totalMediaSpend = mediaSpend;
                        $scope.totalAdvertiserSpend = advertiserSpend;

                        imprCount = clickCount = mediaSpend = advertiserSpend = 0;
                        statsPerPage += $scope.pageSize;
                    }
                }
            }
        }

在视图中

<tr class="campaign-stats-total-tr">
        <td class="campaign-stats-total-td">Total</td>
        <td> - </td>
        <td>{{ totalImprCount | number }}</td>
        <td>{{ totalClickCount | number }}</td>
        <td>{{ calcCtr | number:2}}%</td>
        <td> - </td>
        <td>{{ totalMediaSpend | currency }}</td>
        <td>{{ totalAdvertiserSpend | currency }}</td>
    </tr>

2 个答案:

答案 0 :(得分:1)

如何在重复时添加ng-init="sumFunction(impr, clickCount, mediaSpend, advertiserSpend)"并在页面更改时创建resetData函数?

答案 1 :(得分:0)

我可能已经理解了你,你希望不仅在最后一页上保留页面之间的附加内容。

如果是你使用$ rootScope可能会有运气。这将在您的网页之间共享一个共同范围。