嵌套ng-repeat的项目总和

时间:2017-12-15 21:52:15

标签: javascript angularjs

我正在尝试在ng-repeat中进行一些计算,我想从列表中的每个嵌套ng-repeat中获取总价格。

<div class="Container" ng-repeat="items in list">

  <div class="top">i am in the top {{items.date}}</div>

    <div class="item" ng-repeat="item in items">
      <a>{{item.count}}</a>
      <a ng-init="setTotals(total = (item.count * item.price))">{{item.price}}</a>   
    </div>

  <div class=bottom">total price: {{totalPrice}}</div>

</div>

这是我试图获得的角度范围:

    $scope.setTotals = function (total) {
        $scope.totalPrice = total * total;
    }

但这只是单个项目输出的两倍,我怎样才能获得嵌套ng-repeat中所有项目的总数?

3 个答案:

答案 0 :(得分:0)

假设项目列表如下:

$scope.list = [
    {date: '2017-12-14', items: [
        {count: 3, price: 9},
        {count: 1, price: 20}
    ]},
    {date: '2017-12-15', items: [
        {count: 2, price: 10},
        {count: 5, price: 20}
    ]}
];

并且您希望使用函数计算每日价格总和:

$scope.calculateTotal = function (dayItems) {
    let total = 0;
        for (item of dayItems.items) {
            total += (item.count * item.price);
        };
    return total;
}

html变得像:

<div class="Container" ng-repeat="items in list">

  <div class="top">i am in the top {{items.date}}</div>

    <div class="item" ng-repeat="item in items.items">
      <a>{{item.count}}</a>
      <a>{{item.price}}</a>   
    </div>

  <div class=bottom">total price: {{calculateTotal(items)}}</div>

</div>

working demo plunker。当然,您可以修改代码以满足您的需求,它只是一个示例实现。

答案 1 :(得分:0)

向控制器添加功能:

$scope.getTotalPrice = function(items)
{
    return items.reduce(function(sum, item)
    {
        return (sum + (item.count * item.price));
    }, 0);
};

在html中调用它:

<div class="Container" ng-repeat="items in list">

  <div class="top">i am in the top {{items.date}}</div>

    <div class="item" ng-repeat="item in items">
      <a>{{item.count}}</a>
      <a>{{item.price}}</a>   
    </div>

  <div class=bottom">total price: {{ getTotalPrice(items) }}</div>

</div>

答案 2 :(得分:0)

您可以在此处执行的操作是在控制器中执行计算逻辑,并在视图中显示其结果:

<强> JavaScript的:

$scope.totalPrice = $scope.items..reduce((sum, item) => {
     return (sum + item.count * item.price);
}, 0);

<强> HTML:

<div class="Container" ng-repeat="items in list">

  <div class="top">i am in the top {{items.date}}</div>

  <div class="item" ng-repeat="item in items">
    <a>{{item.count}}</a>
    <a>{{item.price}}</a>
  </div>

  <div class=bottom ">total price: {{totalPrice}}</div>

</div>