Skip to content

Instantly share code, notes, and snippets.

@toddnestor
Last active March 14, 2016 21:03
Show Gist options
  • Save toddnestor/ebbe2be33b5852d55194 to your computer and use it in GitHub Desktop.
Save toddnestor/ebbe2be33b5852d55194 to your computer and use it in GitHub Desktop.
Angular cart sample for Ed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div ng-app="app" ng-controller="myAppController">
<h3>Items</h3>
<ul>
<li ng-repeat="item in possible_items">
{{item.title}}: ${{item.price}}
<input type="number" min="1" ng-init="qty = 1" ng-model="qty" />
<button ng-click="addToCart( item, qty )">Add</button>
</li>
</ul>
<hr>
<h3>Cart</h3>
<ul ng-if="cart_items.length > 0">
<li ng-repeat="item in cart_items">
<input type="number" ng-model="item.qty" /> {{item.item.title}} ${{item.item.price * item.qty}}
<button ng-click="removeFromCart( item )">Remove</button>
</li>
</ul>
<strong ng-if="cart_items.length == 0">You haven't added any items yet...</strong>
<hr>
<strong>Total: ${{calculateTotal()}}</strong>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.2/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script type="text/javascript">
angular.module('app', [])
.controller('myAppController', ['$scope', myAppController]);
function myAppController( $scope ) {
$scope.cart_items = [];
$scope.removeFromCart = function( item ) {
$scope.cart_items = _.without( $scope.cart_items, item );
}
$scope.calculateTotal = function() {
var total = 0;
angular.forEach( $scope.cart_items, function( value ) {
total += value.item.price * value.qty;
} );
return total;
}
$scope.addToCart = function( item, qty ) {
var existing_item = _.findWhere( $scope.cart_items, {item: item } );
if( existing_item )
existing_item.qty += qty;
else {
$scope.cart_items.push({
item: item,
qty: qty
});
}
}
$scope.possible_items = [
{
title: 'item 1',
description: 'this is a cool description',
price: '21.00'
},
{
title: 'item 2',
description: 'this is a cool description',
price: '27.00'
},
{
title: 'item 3',
description: 'this is a cool description',
price: '95.00'
}
];
}
</script>
</body>
</html>
@toddnestor
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment