2017-02-04 106 views
1

我做了一个简单的项目计算,其中我有项目价格,数量和标题存储在一个数组中。我计算的总金额为每个项目:

<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> 
脚本

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 = 

}); 

但问题是,它显示了只有最后的{{totalprice}}计算值项目,而控制台显示每个项目的正确计算$log.log($scope.items[i].price*$scope.items[i].quantity);

请告诉我为什么在输出它只显示最后的计算。提前致谢。

+0

因为你重新计算和重新分配'$ scope.totalprice'价值,这就是为什么最后的值被分配到'$ scope.totalprice' –

+0

OK,请给代码解决方案。 – user3450590

回答

1

您必须拥有totalprice定义的每个项目。

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>

+0

谢谢。但只是好奇:我不能将$ scope.totalprice的值添加到数组中吗?特别是当控制台'$ log.log($ scope.items [i] .price * $ scope.items [i] .quantity);'引发正确的值? – user3450590

+0

我没有得到它,你不需要$ scope.totalvalue – Sajeetharan

+0

我只是说,当我在'$ log.log($ scope.items [i] .price * $ scope.items [i] .quantity)',那么它为什么不反映在{{totalprice}}中。我认为我们可以像$ watch那样做一些更新的值,所以有些类似,不需要在数组中添加'totalprice'。 – user3450590