Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ngBind with multiplication and sum

I have four products and i am taking its quantity from user. these products have fixed price and i want to display total amount in last.

This is my Controller

application.controller('SaleController', function ($scope) {
 $scope.Spaghetti_price=50;
 $scope.Macaroni_price=100;
 $scope.Noodles_price=40;
 $scope.MegaNoodles_price=70;
}

And Here is my view

<div>
<input type="number" class="text-input" ng-model="Spaghetti_qty" />
<input type="number" class="text-input" ng-model="Macaroni_qty"  />
<input type="number" class="text-input" ng-model="Noodles_qty" />
<input type="number" class="text-input" ng-model="MegaNoodles_qty"  />
</div>
<div>
Total Amount: 
<input type="number" class="text-input" ng-model="totalAmount" ng-bind="(Spaghetti_qty*Spaghetti_price)+(Macaroni_qty*Macaroni_price)+(Noodles_qty*Noodles_price)+(MegaNoodles_qty*MegaNoodles_price)"/>
</div>

But above code is not working i am not getting any updated value in total amount textbox. I want live update in amount textbox as user enters quantity for products.

Is any other way to achieve this?

like image 761
Manish Parakhiya Avatar asked Aug 23 '26 00:08

Manish Parakhiya


1 Answers

You need to start with the behavior and model it. So, a behavior of calculated vs. entered is very important.

Specifically, let's define a variable that stores the state of whether the "total" is calculated or not.

$scope.isTotalCalculated = true; // at first it is calculated

We'll also need the variable to hold the total - $scope.totalAmount - it would be updated with each change in quantity, unless $scope.isTotalCalculated === false.

And we'll need the updateTotal() function.

All together, it looks like so:

$scope.isTotalCalculated = true;
$scope.totalAmount = 0;
$scope.updateTotal = updateTotal;

updateTotal(); // initial update of total

function updateTotal(){
   if (!$scope.isTotalCalculated) return;
   $scope.totalAmount = $scope.Spaghetti_price * $scope.Spaghetti_qty + ...
}

Then you just need to wire it up to the View:

<input type="number" ng-model="Spaghetti_qty" ng-change="updateTotal()" />
<input type="number" ng-model="Macaroni_qty"  ng-change="updateTotal()" />
...

<input type="number" ng-model="totalAmount" ng-change="isTotalCalculated = false" />

Demo

like image 192
New Dev Avatar answered Aug 24 '26 12:08

New Dev