2016-03-04 88 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