I have created an Angular Single Page Application that includes a cart feature where users can add items. My goal is to prevent users from adding the same item to the cart more than once.
function CartForm($scope) {
$scope.products = [{
"description": "BB-8 Droid",
"qty": "1",
"cost": "99"
}, {
"description": "C-3PO Droid",
"qty": "1",
"cost": "499"
}, {
"description": "R2-D2 Astromech Droid",
"qty": "1",
"cost": "899"
}, {
"description": "R5-D4 Astromech Droid",
"qty": "1",
"cost": "899"
}, {
"description": "IG-88 Bounty Hunter Droid",
"qty": "1",
"cost": "899"
}];
$scope.invoice = {
items: []
};
$scope.addItem = function(product) {
$scope.invoice.items.push(product);
},
$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;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h2>Shopping Cart Example</h2>
<div ng:controller="CartForm">
<table class="table">
<thead>
<th>Description</th>
<th>Qty</th>
<th colspan="2">Price</th>
</thead>
<tr ng-repeat="product in products">
<td>{{product.description}}</td>
<td>{{product.qty}}</td>
<td>{{product.cost | currency }}</td>
<td>
<button class="btn btn-danger" ng-click="addItem(product)">ADD TO CART</button>
</tr>
</table>
<table class="table">
<tr>
<th>Description</th>
<th>Qty</th>
<th>Cost</th>
<th>Total</th>
<th></th>
</tr>
<tr ng:repeat="item in 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="removeItem($index)">X</a>]
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Total:</td>
<td>{{total() | currency}}</td>
</tr>
</table>
</div>
Check out the live JSFiddle demo here: http://jsfiddle.net/tedleeatlanta/22591h2y/15/