Closed Jesus82 closed 8 years ago
Yes, I have made it work like that; You have to make two functions that you can call on click on your + and - buttons. Here are them respectively:
increaseQuantity: (slug)=> {
let item = ngCart.getItemById(slug);
if (typeof item === 'object') {
item.setQuantity(1, true);
} else {
let bottle = bottles[slug];
ngCart.addItem(bottle.slug, bottle.name, bottle.price, 1, "none");
}
},
decreaseQuantity: (slug)=> {
let item = ngCart.getItemById(slug);
if (item) {
if (item.getQuantity() > 1) {
item.setQuantity(-1, true);
} else {
ngCart.removeItemById(slug)
}
} else {
return false;
}
}
I get my items from my Bottles array, but you can get the picture. A warning here! This will NOT update your LocalStorage because they removed an event broadcast from the item.setQuantity() method.
Thanks for the answer. I have started recently with angular, so my knowledge is very limited, so it may be a very basic question: should I put the functions in my controller or anywhere in the ng-cart directive? Thanks!
You should not edit the sources you get. So you should make a directive, that gives you the + and - buttons, like <cart-quantities/>
something like this. Then inside its $scope you can define these functions.
That way inside the cart-quantitie`s template you can use ng-click="decreaseQuantity()" and so on.
Ok, I get it now, thanks for the answer!
Dont forget to Inject ngCart into your directive.
Thanks for the tip, I will do so!
@dobromir-hristov I am now trying to implement your solution, but I had no success in including the function into the scope. Could you give it a look to see if you can figure out what I'm doing wrong? Thanks!
app.directive('changeQuantity', ['ngCart', function(ngCart){
return {
restrict : 'EA',
scope: {
increaseQuantity = function(slug) {
let item = ngCart.getItemById(slug);
if (typeof item === 'object') {
item.setQuantity(1, true);
} else {
let names = names[slug];
ngCart.addItem(names.slug, names.name, names.price, 1, "none");
}
}
},
templateUrl: {
<button class="btn-masmenos" ng-click="increaseQuantity()">+</button>
}
};
}]);
Change that let item = ...
into a var item =
also the let names
Also your let names = names[slug];
this is not right. I have an object bottles
where i store all my products, in my case bottles of alcohol, then i get only one bottle by its slug thats where let bottle = bottles[slug]
comes in. This is so I could then pass the slug, name and price to the ngCart.addItem
method.
Hi, is it be possible to use +- buttons instead of the select element in the addtocart.html template? (so it would work like the
<button ng-click="item.setQuantity(1, true)">
in cart.html ) Thanks!