AngularJS: Cart example
HTML
<link rel="stylesheet" href="http://d1e24pw9mnwsl8.cloudfront.net/c/bootstrap/css/bootstrap.min.css">
<h2>Shopping Cart Example</h2>
<div ng:controller="CartForm">
<table class="table">
<tr>
<th>Description</th>
<th>Qty</th>
<th>Cost</th>
<th>Total</th>
<th></th>
</tr>
<tr ng:repeat="item in cart.invoice.items">
<td><input type="text" ng:model="item.description"class="input-small"></td>
<td><input type="number" ng:model="item.qty" ng:required class="input-mini"></td>
<td><input type="number" ng:model="item.cost" ng:required class="input-mini"></td>
<td>{{item.qty * item.cost | currency}}</td>
<td>
[<a href ng:click="cart.removeItem($index)">X</a>]
</td>
</tr>
<tr>
<td><a href ng:click="cart.addItem()" class="btn btn-small">add item</a></td>
<td></td>
<td>Total:</td>
<td>{{cart.total() | currency}}</td>
</tr>
</table>
</div>
JavaScript
// note that I've put the same name (myAppName) in the ng-app directive on the body tag!
// declare our app
angular
.module('myAppName', [])
// define the cart controller
.controller('CartForm', ['$scope', 'cartService', function($scope, cartService) {
$scope.cart = cartService;
}])
// define the cart api
.factory('cartService', [function() {
// this will be the api holder
var cartApi = {};
cartApi.invoice = {
items: [{
qty: 10,
description: 'item',
cost: 9.95}]
};
cartApi.addItem = function() {
cartApi.invoice.items.push({
qty: 1,
description: '',
cost: 0
});
};
cartApi.removeItem = function(index) {
cartApi.invoice.items.splice(index, 1);
};
cartApi.total = function() {
var total = 0;
angular.forEach(cartApi.invoice.items, function(item) {
total += item.qty * item.cost;
});
return total;
}
return cartApi;
}])