How to calculate the total sum of elements in an array element using AngularJS
I have a table that has a column named price, I want to calculate the total cost of items. What I've tried doesn't add the whole total price, it displays the same values ββas in the table row. I have included a link to jsbin.
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<html>
<div ng-app>
<div ng-controller="ShoppingCartCtrl">
<br />
<table border="1">
<thead>
<tr>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Remove Item</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
<td><input type="button" value="Remove" ng-click="removeItem($index)" /></td>
</tr>
</tbody>
</table>
<br />
<div>Total Price: {{totalPrice()}}</div>
<br />
<table>
<tr>
<td>Name: </td>
<td><input type="text" ng-model="item.Name" /></td>
</tr>
<tr>
<td>Price: </td>
<td><input type="text" ng-model="item.Price" /></td>
</tr>
<tr>
<td>Quantity: </td>
<td><input type="text" ng-model="item.Quantity" /></td>
</tr>
<tr>
<td colspan="2"><input type="Button" value="Add" ng-click="addItem(item)" /> </td>
</tr>
</table>
</div>
</div>
</html>
function ShoppingCartCtrl($scope) {
$scope.items = [
{Name: "Soap", Price: "25", Quantity: "10"},
{Name: "Shaving cream", Price: "50", Quantity: "15"},
{Name: "Shampoo", Price: "100", Quantity: "5"}
];
$scope.addItem = function(item) {
$scope.items.push(item);
$scope.item = {};
};
$scope.totalPrice = function(){
var total = 0;
for(count=0;count<$scope.items.length;count++){
total +=$scope.items[count].Price + $scope.items[count].Price;
}
return total;
};
$scope.removeItem = function(index){
$scope.items.splice(index,1);
};
}
+3
source to share
2 answers
Your problem is that you have defined the price and quantity as a string, not as numbers. You have two options
- Define price and quantity as numbers, not strings, which is the best solution
-
use parseInt or parseFloat during computation
function ShoppingCartCtrl($scope) { $scope.items = [ {Name: "Soap", Price: 25, Quantity: 10}, {Name: "Shaving cream", Price: 50, Quantity: 15}, {Name: "Shampoo", Price: 100, Quantity: 5} ]; $scope.addItem = function(item) { $scope.items.push(item); $scope.item = {}; }; $scope.totalPrice = function(){ var total = 0; for(count=0;count<$scope.items.length;count++){ total += $scope.items[count].Price + $scope.items[count].Price; } return total; }; $scope.removeItem = function(index){ $scope.items.splice(index,1); }; }
+3
source to share
Similar to what Ghyath Serhal said, use this code instead of what you have
$scope.items = [
{Name: "Soap", Price: 25, Quantity: 10},
{Name: "Shaving cream", Price: 50, Quantity: 15},
{Name: "Shampoo", Price: 100, Quantity: 5}
];
I see no need for the integer values ββin this instance to be strings, so using them as integers will solve your problem.
+1
source to share