AngularJS: Cart example

by pkozlowski_opensource

HTML

<div ng:controller="CartForm">
    <table>
        <tr>
            <th>Qty</th>
            <th>Description</th>
            <th>Cost</th>
            <th>Total</th>
            <th></th>
        </tr>
        <tr ng:repeat="item in invoice.items">
            <td><input type="number" ng:model="item.qty" ng:required></td>
            <td><input type="text" ng:model="item.description"></td>
            <td><input type="number" ng:model="item.cost" ng:required></td>
            <td>{{item.qty * item.cost | currency}}</td>
            <td>
                [<a href ng:click="removeItem($index)">X</a>]
            </td>
        </tr>
        <tr>
            <td><a href ng:click="addItem()">add item</a></td>
            <td></td>
            <td>Total:</td>
            <td>{{total() | currency}}</td>
        </tr>
    </table>
</div>

CSS

.ng-invalid { border: 1px solid red; } 
body { font-family: Arial,Helvetica,sans-serif; }
body, td, th { font-size: 14px; margin: 0; }
table { border-collapse: separate; border-spacing: 2px; display: table; margin-bottom: 0; margin-top: 0; -moz-box-sizing: border-box; text-indent: 0; }
a:link, a:visited, a:hover { color: #5D6DB6; text-decoration: none; }
.error { color: red; }

JavaScript

function CartForm($scope) {
    $scope.invoice = {
        items: [{
            qty: 10,
            description: 'gadget',
            cost: 9.95}]
    };
    
    $scope.addItem = function() {
        $scope.invoice.items.push({
            qty: 1,
            description: '',
            cost: 0
        });
    },

    $scope.removeItem = function(index) {
        $scope.invoice.items.splice(index, 1);
    },

    $scope.total = function() {
        var total = 0;
        angular.forEach($scope.invoice.items, function(item) {
            total += item.qty * item.cost;
        })

        return total;
    }
}