AngularJS Calculating Total with ng-repeat

created by ozkary.com

by Sajeetharan Sinnathurai

HTML

<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-app="app">
    <div ng-controller="app.invoice" class="container">
        <table class="table table-condense">
            <caption>ozkary.com Sports Products Invoice</caption>
            <thead>
                <tr class="bg-primary">
                    <th>Name</th>
                    <th>Quantity</th>
                    <th>Item Cost</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in items" ng-init="setTotals(item)">
                    <td>{{item.name}}</td>
                    <td>{{item.quantity}}</td>
                    <td>{{item.unitCost | number:2}}</td>
                    <td>{{item.total | number:2}}</td>
                </tr>
            </tbody>
            <tfoot>
                <tr class="bg-warning">
                    <td>Totals</td>
                    <td>{{invoiceCount}}</td>
                    <td></td>                    
                    <td>{{invoiceTotal | number:2}}</td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

JavaScript

var app = angular.module('app', []);
app.controller('app.invoice', ['$scope', invoice]);

function invoice($scope) {
    $scope.items = [{
        name: 'Baseball Bats',
        quantity: 2,
        unitCost: 75
    }, {
        name: 'Soccer Balls',
        quantity: 5,
        unitCost: 15
    }, {
        name: 'Baseball Gloves',
        quantity: 3,
        unitCost: 40
    }];
    
    $scope.invoiceCount = 0;
    $scope.invoiceTotal = 0;
    
    $scope.setTotals = function(item){
        if (item){
            item.total = item.quantity * item.unitCost;
            $scope.invoiceCount += item.quantity;
            $scope.invoiceTotal += item.total;
        }
    }
}