AngularJS Sample
AngularJS - Sample eCommerce App with Inventory & Shopping Cart
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script>
<div class="root" ng-controller="mainController">
<div>
<h4>Products</h4>
<div>
<ul>
<li ng-repeat="product in inventory" class="product">
<div><span>{{product.name}}</span>
<span>{{product.count}}</span>
<button ng-click="addToCart(product.id)" ng-disabled="product.count === 0">Add</button>
</div>
</li>
</ul>
</div>
</div>
<div>
<h4>Shopping Cart</h4>
<div>
<ul>
<li ng-repeat="product in itemsInCart" class="product">
<div> <span>{{product.name}}</span>
<span>{{product.count}}</span>
<button ng-click="removeFromCart(product.id)" ng-disabled="product.count === 0">Remove</button>
</div>
</li>
</ul>
</div>
</div>
CSS
.root > div {
width: 47.5%;
display: inline-block;
padding: 3px;
border: solid 1px #ddd;
vertical-align: top;
}
.product {
list-style: none;
}
.product > div > * {
display: inline-block;
width: 30%;
}
* {
font-family:"Consolas", monospace;
}
h4 {
text-decoration: underline;
}
JavaScript
rtvar app = angular.module('myApp', []);
app.factory('GenericList', function () {
return function () {
this.items = [];
this._lookup = {};
this.refreshLookup = function () {
for (var i = 0, len = this.items.length; i < len; i++) {
this._lookup[this.items[i].id] = this.items[i];
}
};
this.add = function (item) {
if (this._lookup[item.id]) {
this._lookup[item.id].count++;
} else {
this.items.push(item);
this.refreshLookup();
}
};
this.remove = function (itemId) {
var item = this._lookup[itemId];
if (item.count > 0) {
item.count--;
return {
id: itemId,
name: item.name,
count: 1
};
} else {
return null;
}
};
};
});
app.service('inventory', ['GenericList', function (List) {
var inventory = new List();
inventory.items = [{
id: 1,
name: 'Shoes',
count: 30
}, {
id: 2,
name: 'TV',
count: 5
}, {
id: 3,
name: 'Car',
count: 2
}];
inventory.refreshLookup();
return inventory;
}]);
app.service('shoppingCart', ['GenericList', function (List) {
return new List();
}]);
app.controller('mainController', ['$scope', 'inventory', 'shoppingCart', function ($scope, inventory, cart) {
$scope.inventory = inventory.items;
$scope.itemsInCart = cart.items;
$scope.addToCart = function (itemId) {
cart.add(inventory.remove(itemId));
};
$scope.removeFromCart = function (itemId) {
inventory.add(cart.remove(itemId));
};
}]);
angular.element(document).ready(function () {
angular.bootstrap(document, ['myApp']);
});