使用角度 js 获取 ng-repeat 内的总和值

Get total sum values within ng-repeat with angular js

本文关键字:ng-repeat 获取 js      更新时间:2023-09-26

我用ng-repeat来重复json数组。我使用 dayDiff() 函数计算了夜晚。现在我想获得所有发票的总晚上。我正在使用angularjs。

如何获得所有发票的总晚数?

<table class="table" ng-show="filteredItems > 0">
    <tr>
        <td>No</td>
        <td>Invoice No</td>
        <td>Name</td>
        <td>Eamil</td>
        <td>Room Name</td>
        <td>Check In Date</td>
        <td>Check Out Date</td>
        <td>No. Room</td>
        <td>Night(s)</td>
        <td>Booking Date</td>
        <td>Amount</td>
    </tr>
    <tr ng-repeat="data in filtered = (list | filter:search ) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
        <td>{{$index+1}}</td>
        <td>{{data.invoicenumber}}</td>
        <td>{{data.firtname}}{{data.lastname}}</td>
        <td>{{data.email}}</td>
        <td>{{data.roomname}}</td>
        <td ng-model='fromDate'>{{data.cidt}}</td>
        <td ng-model='toDate'>{{data.codt}}</td>
        <td>{{data.qty}}</td>
        <td ng-model='night'>{{dayDiff(data.cidt,data.codt)}}</td>
        <td>{{data.bdt}}</td>
        <td>{{data.btotal}}</td>
    </tr>
</table>

您需要首先添加额外的行。这个额外的行将如下所示:

<tr>
    <td colspan="11">Total nights: {{calcTotal(filtered)}}</td>
</tr>

然后在控制器中,您需要添加一个函数来计算夜晚,例如

$scope.calcTotal = function(filtered){
     var sum = 0;
     for(var i = 0 ; i<filtered.length ; i++){
        sum = sum + filtered[i].nights;
     }
     return sum;
};

首先,您可以为 JSON 模型使用工厂来存储计算的夜晚:

// We inject the dayDiff function via the dayDiffService service
angular.factory('invoice', ['dayDiffService', function(dayDiffService) {
    var Invoice = function(data) {
        // merge json properties to self
        angular.merge(this, data);
        // we compute the night(s)
        this.nights = dayDiffService.dayDiff(data.cidt, data.codt);
    }
    return Invoice;
}]);

然后,在控制器中,添加一个函数来汇总筛选列表中的夜晚:

angular.controller('invoicesCtrl', ['$scope', 'invoice', function($scope, Invoice) {
    $scope.list = [];
    // let's say that JSON holds your json model from http's response
    $scope.list = JSON.map(function() { 
        return new Invoice(i) 
    });
    $scope.sumNights = function(filtered) {
        filtered.reduce(function(sum, invoice) {
            sum += invoice.nights;
            sum
        }, 0);
    }
}]);

然后,在 html 中添加一个新行以显示计算结果:

<div ng-controller="invoicesCtrl as vm">
    <table>
        ...
        <tbody>
            <tr ng-repeat="data in filtered = (vm.list | filter:search ) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
                <td>{{$index+1}}</td>
                ...
                <tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="8"></td
                <td>{{vm.sumNights(filtered)}}</td
                <td colspan="2"></td
            </tr>
        </tfoot>
    </table>
</div>