2017-02-04 129 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