2016-03-04 56 views
1

我擁有包含物品,數量和價格的表格。我可以根據數量變化更新每行的價格。如何使用ng-repeat計算總計

但現在我想添加所有價格並顯示總數。我確實寫了一個函數,但沒有幫助。

查看

<table class="table"> 
    <thead> 
     <th>Items</th> 
     <th>Description</th> 
     <th>Quantity</th> 

     <th>Price</th> 
    </thead> 
    <tbody ng-repeat="item in items"> 

    <td><img ng-src={{item.ImageUrl}} title="{{item.Name}}" 
      class="img-thumbnail" height="100" width="100" ><br/> 
     {{item.Name}} 
    </td> 
    <td>{{item.Description}}</td> 
    <td><input type="number" min="0" max="{{item.Quantity}}" ng-model="currentQuantity"/></td> 
    <td ng-model="currentPrice">{{item.Price*currentQuantity}}</td> 
    </tbody> 
    <tfoot> 
     <tr> 
      <td/> 
      <td/> 
      <td>Total</td>  
      <td>{{Total()}}</td> 
     </tr> 
    </tfoot> 
</table> 

型號&控制器:

(function() { 
    var app = angular.module("FoodItems", []); 

    var serviceUrl = "http://localhost/MkitechenService/Api/FoodItems"; 

    var MainController = function($scope, $http) { 


    $scope.currentQuantity=1; 
    $scope.currentPrice=0; 

    $scope.Total = function() 
    { 
     currentPrice +=currentPrice; 
     return 100; 
    }; 

var onItemsLoaded = function(response) { 
    console.log(response.data); 
    $scope.items = response.data; 

}; 

var onError = function(reason) { 
    console.log(reason.message); 

}; 

$http.get(serviceUrl).then(onItemsLoaded, onError); 


    }; 


    app.controller("MainController", MainController); 

}()); 
+1

這個'< td ng-model'沒有意義 – Grundy

+0

此外,輸入的'ng-model'應該是'item.currentQuantity'。 –

回答

3

ng-repeat創建自己的範圍,

ng-model="currentQuantity" 

廣告d財產currentQuantity到這個範圍,所以你不能在這個範圍之外。

但你可以將其保存在item,只是用

ng-model="item.currentQuantity" 

之後,在Total功能,你應該剛剛過去的項目收集,總結item.currentQuantity,這樣

$scope.Total = function() 
{ 
    return $scope.items.reduce(function(total,item){ 
     return total + (item.currentQuantity*item.Price || 0);//for case when this filed not filled 
    },0); 
}; 
+0

這個工程,更新總數量,但有一個問題。當我更改數量時,它只是更新總價格,而不是更新該行的價格欄。以前更新的是行價,而不是總價。我想同時使用 – Simsons

+0

@Simsons,您是否將'item.Price * currentQuantity'更改爲'item.Price * item.currentQuantity'? – Grundy

+1

謝謝,爲什麼這個方法被命名爲.reduce !! – Simsons