Patrickkx
Patrickkx

Reputation: 1870

AngularJS: Auto-update the totalPrice value

I'm in progress of my first simple app, I have experienced many problems already and this one is just the next problem in this long serie.

I have to let the user choose the quantity of each product. There were few ways to do it, I chose that one, in which the user chooses the product he wants, and then - on the shopping list - he can adjust the amount of the product as he wishes. I don't know if its a proper way, but like I said this is my first ap and I've started learning AngularJS yesterday.

I have to combine somehow the: total += $scope.itemsToBuy[i].price * TheQuantityOfEachElem;

I've already tried, but failed miserably. This is how it is when you start something...

My first idea is to take the value of the nth input and then multiply it with the price of elem. But the problem is that I don't know how to set this combination.

Sorry for such a long story, if you have any ideas, proposals or hints just let me know. I will appreciate it as always. Thank you in advance.

The jsfiddle of my app so far: https://jsfiddle.net/scgsc7or/14/

The totalPrice works, but it doesn't include the quantity.

Upvotes: 0

Views: 55

Answers (2)

Gourav Garg
Gourav Garg

Reputation: 2911

@mark is right. But if you do this at first it will give NaN in total price as quantity is not defined when you add a item in cart.

Either add 1 in quantity or use below code:

total += $scope.itemsToBuy[i].price * ($scope.itemsToBuy[i].quantity?$scope.itemsToBuy[i].quantity:1);

Upvotes: 5

Mark Adelsberger
Mark Adelsberger

Reputation: 45649

It looks like the quantity up/down buttons are updating itemsToBuy[i].qty, right? So what's wrong with

total += $scope.itemsToBuy[i].price * $scope.itemsToBuy[i].qty;

or something like that when calculating the total price? (You may have to make sure qty is initialized properly when adding an element to itemsToBuy)

Upvotes: 1

Related Questions