NG Cart
by Rob Rothe
HTML
<div ng-app="app">
<div ng-controller="CartCtrl as ctrl">
<h4>Items ({{ctrl.cart.length}})</h4>
<table>
<tr ng-repeat="item in ctrl.cart track by $index">
<td>{{item.name}}</td>
<td>${{item.price}}</td>
<td>
<button ng-click="ctrl.removeFromCart(item)">-</button>
</td>
</tr>
<tr>
<td>Total: <strong>${{ctrl.total}}</strong></td>
</tr>
</table>
<hr>
</div>
<div ng-controller="ItemsCtrl as ctrl">
<table>
<tr ng-repeat="item in ctrl.items">
<td>{{item.name}} - ${{item.price}}</td>
<td>
<button ng-click="ctrl.addToCart(item)">+</button>
</td>
</tr>
</table>
</div>
<hr>
<div ng-controller="CartCtrl as ctrl">
<h4>Items ({{ctrl.cart.length}})</h4>
<table>
<tr ng-repeat="item in ctrl.cart track by $index">
<td>{{item.name}}</td>
<td>${{item.price}}</td>
<td>
<button ng-click="ctrl.removeFromCart(item)">-</button>
</td>
</tr>
<tr>
<td>Total: <strong>${{ctrl.total}}</strong></td>
</tr>
</table>
<hr>
</div>
JavaScript
angular
.module('app', [])
.controller('ItemsCtrl', ItemsCtrl)
.controller('CartCtrl', CartCtrl)
.factory('Service', Service);
function ItemsCtrl(Service) {
var vm = this;
vm.items = Service.items;
vm.addToCart = addToCart;
function addToCart(item) {
Service.addToCart(item);
}
}
function CartCtrl(Service, $scope) {
var vm = this;
vm.cart = Service.cart;
vm.total = Service.total;
vm.removeFromCart = removeFromCart;
$scope.$on('total_update', function(event, total) {
vm.total = total;
});
function removeFromCart(item) {
Service.removeFromCart(item);
vm.total = Service.total;
}
}
function Service($rootScope) {
var service = {
items: [{
name: 'Pencil',
price: .99
}, {
name: 'Pen',
price: 1.99
}, {
name: 'Paper',
price: .49
}],
total: 0,
cart: [],
addToCart: addToCart,
removeFromCart: removeFromCart,
updateTotal: updateTotal
};
return service;
function addToCart(item) {
service.cart.push(item);
updateTotal();
}
function removeFromCart(item) {
var idx = service.cart.indexOf(item);
service.cart.splice(idx, 1);
updateTotal();
}
function updateTotal() {
var total = 0;
for (var i = 0; i < service.cart.length; i++) {
var product = service.cart[i];
total += parseFloat(product.price);
}
service.total = total.toFixed(2);
$rootScope.$broadcast('total_update', service.total);
}
}