Created
September 29, 2014 11:11
-
-
Save gajus/07145f189dc7a19dd03f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular | |
.module('cart', []); | |
.factory('cart', function () { | |
var cartData = {}; | |
return { | |
addProduct: function (id, name, price) { | |
var addToExistingItem = false; | |
for (var i = 0; i < cartData.length; i++) { | |
if (cartData[i].id == id) { | |
cartData[i].count++; | |
addedToExistingItem = true; | |
break; | |
} | |
} | |
if (!addedToExistingItem) { | |
cartData.push({ | |
count: 1, id: id, price: price, name: name | |
}); | |
} | |
}, | |
removeProduct: function (id) { | |
for (var i = 0; i < cartData.length; i++) { | |
if (cartData[i].id == id) { | |
cartData.splice(i, 1); | |
break; | |
} | |
} | |
}, | |
getProducts: function () { | |
return cartData; | |
} | |
} | |
}) | |
.directive('cartSummary', function (cart) { | |
return { | |
restrict: 'E', | |
templateUrl: './static/js/components/cart/cartSummary.html', | |
controller: function ($scope) { | |
var cartData = cart.getProducts(); | |
$scope.total = function () { | |
var total = 0; | |
for (var i = 0; i < cartData.length; i++) { | |
total += (cartData[i].price * cartData[i].count); | |
} | |
return total; | |
}; | |
$scope.itemCount = function () { | |
var total = 0; | |
for (var i = 0; i < cartData.length; i++) { | |
total += cartData[i].count; | |
} | |
return total; | |
}; | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment