Reputation: 341
i am making a simple item calulation where i have item price, quantity and title stored in a array. I am calculating the total amount for each of the items:
<div ng-controller="myctrl">
<table>
<tr ng-repeat="itms in items"><td>{{itms.title}} <input type="text" ng-model="itms.quantity"/>{{itms.price}} - {{totalprice}}</td></tr>
</table>
in script:
app.controller("myctrl", function($scope, $log) {
$scope.items= [
{title: 'Paint Pots', quantity: 8, price: 3.95},
{title: 'Polka Pots', quantity: 17, price: 6.95},
{title: 'Pebbles', quantity: 5, price: 12.95}
]
//$log.log($scope.items[0].title);
//totalprice=quantity*price
$scope.totalprice=0;
for(var i=0; i<$scope.items.length; i++){
$log.log($scope.items[i].price*$scope.items[i].quantity);
//console.log($scope.items[i].price * $scope.items[i].quantity);
$scope.totalprice = $scope.items[i].price * $scope.items[i].quantity;
}
///$scope.totalprice =
});
but the problem is that it is showing the calculated value of {{totalprice}} for only the last item, whereas the console shows the right calculation for each item in $log.log($scope.items[i].price*$scope.items[i].quantity);
Please tell me why in output it is showing only last calculation. Thanks in advance.
Upvotes: 1
Views: 38
Reputation: 222582
You nee to have totalprice
for each item defined.
DEMO
var app = angular.module('sampleApp', []);
app.controller("myCtrl", function($scope) {
$scope.items= [
{title: 'Paint Pots', quantity: 8, price: 3.95,totalprice:0},
{title: 'Polka Pots', quantity: 17, price: 6.95,totalprice:0},
{title: 'Pebbles', quantity: 5, price: 12.95,totalprice:0}
];
$scope.totalprice=0;
for(var i=0; i<$scope.items.length; i++){
$scope.items[i].totalprice = $scope.items[i].price * $scope.items[i].quantity;
}
});
<!DOCTYPE html>
<html ng-app="sampleApp" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<table>
<tr ng-repeat="itms in items"><td>{{itms.title}} <input type="text" ng-model="itms.quantity"/>{{itms.price}} - {{itms.totalprice}}</td></tr>
</table>
</body>
</html>
Upvotes: 1