I'm doing a shopping cart with AngularJs, but I'm having trouble adding products to the shopping cart. I think error is on my Controller:
My data.json:
{
"items": [
{
"product": {
"name": "Smartphone",
"price": {
"value": 3509.10,
}
}
},
{
"product": {
"name": "Lenovo ",
"price": {
"value": 2599.00,
}
}
}
]
}
my controller.js :
var app = angular.module("list", []);
app.controller("ListCtrl", ["$scope", "$http", function($scope, $http) {
$scope.products = [];
$http({ method: 'GET', url: 'data.json'})
.success(function(data) {
angular.forEach(data.items, function(item, index) {
$scope.products.push(item.product);
});
});
}
$scope.carts=[];
$scope.add_cart = function(product){
if(product){
$scope.carts.push({ p_name: product.name, p_valor:product.price.value,);
}
}
$scope.total = 0;
$scope.setTotals = function(cart){
if(cart){
$scope.total += cart.p_valor;
}
}
$scope.remove_cart = function(cart){
if(cart){
$scope.carts.splice($scope.carts.indexOf(cart), 1);
$scope.total -= cart.p_valor;
}
}
]);
my html:
<body ng-controller="ListCtrl" ng-app="list">
<ul ng-repeat="product in products">
<li>{{product.name}} </li>
<li>{{product.price.value}}</li>
<li><button type = "button" ng-click = "add_cart(product)"> Add to cart</button></li>
</ul><br>
<ul ng-repeat = "cart in carts" ng-init = "setTotals(cart)">
<li>{{cart.p_name}}</li>
<li>{{cart.p_price}}</li>
<li><button type = "button" ng-click = "remove_cart(cart)">X</button>
</li>
</ul>
<ul>
<li>{{total}}</li>
</ul>
</body>
I need the button add to cart to work correctly, bringing the product name and the value of the product. I also need it to bring the total value and also need to remove the product when clicking button remove cart.
Ty for Help guys!