-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
123 lines (105 loc) · 2.81 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
angular.module('shop', [])
.controller('mainController', MainController)
.factory('shop', Shop)
.factory('shoppingCart', ShoppingCart)
/**
* Shop factory
* everything related to the app (e.g. getItems)
*/
function Shop() {
return {
getItems: function() {
// shopItems can be stored in a sperate JSON file or in a db
// to keep it simple here we're using a static js object
// e.g. return $http.get('shopItems.json').then(function(json) { return json.data});
return {
sections: [{
title: 'Please enter quantity:',
items: [
{
title: 'Large Pizza',
price: 19.99
},
{
title: 'Large Poutine',
price: 29.99
},
{
title: 'Donair Pizza',
price: 39.99
}
]
},
{
title: 'Your order:',
items: [
]
}
]
};
}
}
}
/**
* Manages the current shopping cart of user
* (summing prices & currently selected items)
*/
function ShoppingCart() {
var factory = {
total: 0,
cartItems: [],
updateItem: updateItem,
updateTotal: updateTotal,
checkCart: checkCart,
checkout: checkout
};
return factory;
function updateItem(evt, item) {
var itemElement = evt.target;
checkCart(item, itemElement.checked);
factory.total = calcTotal();
}
function calcTotal() {
newTotal = 0;
angular.forEach(factory.cartItems, function(item) {
//console.log('calc tot', item);
newTotal += item.checked ? ( item.quantity * item.price ) : 0;
});
return newTotal;
}
function checkCart(item, checked) {
var cartItems = factory.cartItems,
cartIndex = cartItems.indexOf(item);
if ( checked ) {
if ( cartIndex == -1 ) {
cartItems.push(item);
//console.log('added item', cartItems);
}
cartIndex = cartItems.indexOf(item);
angular.extend(cartItems[cartIndex], {
checked: true,
quantity: parseInt(item.quantity || 1)
});
}
else {
cartItems[cartIndex].checked = false;
}
}
function updateTotal(item) {
item.checked = parseInt(item.quantity) > 0;
checkCart(item, item.checked);
factory.total = calcTotal();
}
function checkout() {
// later here would go a checkout page/popup
alert(JSON.stringify(factory.cartItems.map(function(item) {
return item.checked ? item: undefined;
})) + 'total: '+ factory.total);
}
}
function MainController(shop, shoppingCart) {
var vm = this,
cart = [];
vm.sections = shop.getItems().sections;
vm.cart = shoppingCart;
}