AngularJS: Cart example
HTML
<script src="http://docs-next.angularjs.org/angular-0.10.6.min.js"></script>
<div ng:app 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() {
this.invoice = { items: [{ qty: 10, description: 'gadget', cost: 9.95 }] };
}
CartForm.prototype = {
addItem: function () {
this.invoice.items.push({ qty: 1, description: '', cost: 0});
},
removeItem: function (index) {
this.invoice.items.splice(index, 1);
},
total: function () {
var total = 0;
angular.forEach(this.invoice.items, function (item) {
total += item.qty * item.cost;
})
return total;
}
};