AngularJS: Cart example
by Iftakharul Alam
HTML
<link rel="stylesheet" href="http://d1e24pw9mnwsl8.cloudfront.net/c/bootstrap/css/bootstrap.min.css">
<h2>Shopping Card Example</h2>
<div ng:controller="CartForm">
<table class="table">
<tr>
<th>Description</th>
<th>Qty</th>
<th>Option</th>
<th>Total</th>
<th></th>
</tr>
<tr ng:repeat="item in cart.items">
<td>
<select ng-model="item.product" ng-options="p.name for p in products"></select>
</td>
<td>
<input type="number" ng:model="item.qty" ng:required class="input-mini">
</td>
<td <select ng-model="item.option" ng-options="o for o in item.product.options">
</select>
</td>
<td>{{item.qty * item.product.cost | currency}}</td>
<td>[<a href ng:click="removeItem($index)">X</a>]</td>
</tr>
<tr>
<td><a href ng:click="addItem()" class="btn btn-small">add item</a>
</td>
<td></td>
<td>Total:</td>
<td>{{total() | currency}}</td>
</tr>
</table>
</div>
JavaScript
function CartForm($scope) {
$scope.cart = {
items: [{
qty: 2,
cost: 0
}]
};
$scope.products = [{
name: 'Normal Product',
cost: 25,
options: ["Option #1", "Option #2"]
},
{
name: 'Cool Product',
cost: 100,
options: ["Option #1", "Option #2"]
}, {
name: 'Sick Produckt',
cost: 150,
options: ["Option #1", "Option #2"]
}];
$scope.addItem = function () {
$scope.cart.items.push({
qty: 1,
});
},
$scope.removeItem = function (index) {
$scope.cart.items.splice(index, 1);
},
$scope.total = function () {
var total = 0;
angular.forEach($scope.cart.items, function (item) {
total += item.qty * item.product.cost;
})
return total;
}
}