-->

Angularjs ng-repeat running total based on value

2019-07-11 04:00发布

问题:

Working in angularjs and looking to keep a running total based on a value retrieved from the data. The following code always returns the full total value for all items.

<div ng-repeat="child in pItem.childItems | orderBy:'displayOrder'" ng-init="$parent.totalValue = $parent.totalValue + child.field[0].value">

Changing that from the parent scope to the child clears the totalValue on each repeat. So the value always equals the child value just for that one item.

I'm looking for something which returns similar to the following. Where Item1 has a value 2, Item2 a value 3, and Item3 a value 4.

  1. Item1 2
  2. Item2 5
  3. Item3 9

回答1:

Try something like this, this should do the trick:

<div 
  ng-repeat="child in pItem.childItems | orderBy:'displayOrder'" 
  ng-init="child.totalValue = pItem.childItems[$index-1].totalValue + child.field[0].value">
    {{child.field[0].value}} {{child.totalValue}}
</div>

So you basically sum with the previous totalValue result.