hollyquinn
hollyquinn

Reputation: 652

AngularJS Sum of ng-repeat column

I am trying to get the sum of each of my columns in a table that is using ng-repeat. I followed an example I found online, but it's loading 0 for the subtotal.

Here's the filter I've got in my controller:

.filter('sumByKey', function() {
    return function(data, key) {
        if (typeof(data) === 'undefined' || typeof(key) === 'undefined') {
            return 0;
        }

        var sum = 0;
        for (var i = data.length - 1; i >= 0; i--) {
            sum += parseInt(data[i][key]);
        }

        return sum;
    };
});

Then my view looks like this:

 <table class="table table-bordered table-hover table-responsive">
    <thead>            
    <tr>
        <th>
            Date Ordered
        </th>
        <th>
            Retail
        </th>
        <th>
            Airtime
        </th>
        <th>
            Spiff
        </th>
        <th>
            Retail
        </th>
        <th>
            Cost
        </th>
        <th>
            Profit
        </th>
    </tr>
    </thead>
    <tbody>
        <tr ng-repeat="sale in vm.sales">
            <td>
                {{ sale.dateOrdered }}
            </td>
            <td>
                {{ sale.firstLoadRetail}}
            </td>
            <td>
                {{ sale.instantProfitAirTime }}
            </td>
            <td>
                {{ sale.instantProfitSpiff }}
            </td>
            <td>
                {{ sale.netRetail }}
            </td>
            <td>
                {{ sale.netCost }}
            </td>
            <td>
                {{ sale.netProfit }}
            </td>
        </tr>
        <tr>
            <th>
                Subtotal
            </th>
            <td >{{ sales | sumByKey : 'firstLoadRetail'  }}</td>
            <td>{{ sales | sumByKey : 'instantProfitAirTime' }}</td>
            <td>{{ sales | sumByKey : 'instantProfitSpiff' }}</td>
            <td>{{ sales | sumByKey : 'netRetail' }}</td>
            <td>{{ sales | sumByKey : 'netCost' }}</td>
            <td>{{ sales | sumByKey : 'netProfit' }}</td>
        </tr>
    </tbody>
</table>

What am I doing wrong? Thanks in advance.

Upvotes: 0

Views: 319

Answers (1)

Reactgular
Reactgular

Reputation: 54771

You forgot the vm. part.

        <td >{{ vm.sales | sumByKey : 'firstLoadRetail'  }}</td>
        <td>{{ vm.sales | sumByKey : 'instantProfitAirTime' }}</td>
        <td>{{ vm.sales | sumByKey : 'instantProfitSpiff' }}</td>
        <td>{{ vm.sales | sumByKey : 'netRetail' }}</td>
        <td>{{ vm.sales | sumByKey : 'netCost' }}</td>
        <td>{{ vm.sales | sumByKey : 'netProfit' }}</td>

Upvotes: 1

Related Questions