13

我会先说我对 AngularJS 很陌生,所以如果我的思维方式偏离基础,请原谅我。我正在使用 AngularJS 编写一个非常简单的单页报告应用程序,肉和土豆当然是使用角度模板系统自己生成报告。我有很多报告要从类似 Jinja 的语法转换过来,而且我很难复制任何类型的计数器或运行制表功能。

前任。

{% set count = 1 %}
{% for i in p %}
  {{ count }}
  {% set count = count + 1 %}
{% endfor %}

在我的控制器中,我定义了一个变量$scope.total = 0;,然后我可以毫无问题地访问模板内部。我不太清楚的是如何total从一个ng-repeat元素中增加它。我想这看起来像 -

<ul>
    <li ng-repeat="foo in bar">
        {{ foo.baz }} - {{ total = total + foo.baz }}
    </li>
</ul>
<div> {{ total }} </div>

这显然不起作用,也没有类似的东西{{ total + foo.baz}},提前感谢您的任何建议。

4

3 回答 3

33

如果您想要的只是一个计数器(根据您的第一个代码示例),请查看 $index,它包含包含 ngRepeat 中的当前(基于 0)索引。然后只显示总数的数组长度。

<ul>
    <li ng-repeat="item in items">
        Item number: {{$index + 1}}
    </li>
</ul>
<div>{{items.length}} Items</div>

如果您想要重复项目中的特定字段的总和,例如价格,您可以使用过滤器执行此操作,如下所示。

<ul>
    <li ng-repeat="item in items">
        Price: {{item.price}}
    </li>
</ul>
<div>Total Price: {{items | totalPrice}}</div>

和过滤功能:

app.filter("totalPrice", function() {
  return function(items) {
    var total = 0, i = 0;
    for (i = 0; i < items.length; i++) total += items[i].price;
    return total;
  }
});

或者,为了提高可重用性,一个通用的过滤函数:

  app.filter("total", function() {
    return function(items, field) {
      var total = 0, i = 0;
      for (i = 0; i < items.length; i++) total += items[i][field];
      return total;
    }
  });

这将被用作:

<div>Total price: {{items | total:'price'}}</div>
于 2012-10-22T12:28:47.147 回答
5

我需要运行总计而不是简单的总计,所以我添加了@TimStewart 留下的内容。这里的代码:

app.filter("runningTotal", function () {
    return function(items, field, index) {
        var total = 0, i = 0;
        for (i = 0; i < index+1; i++) {
            total += items[i][field];
        }
        return total;
    };
});

要在列中使用它,您只需执行以下操作:

<div>Total price: {{items | runningTotal:'price':$index}}</div>
于 2014-06-24T20:42:45.363 回答
0

我不确定我是否完全理解这个问题,但只需要显示您正在迭代的对象中的总数吗?只需设置$scope.total为数组的长度(bar在上面的示例中)。所以,$scope.total = $scope.bar.length;

如果你想要所有foo.baz属性的总和,你只需要在你的控制器中计算它。

$scope.total = 0;
angular.forEach($scope.bar, function(foo) {
    $scope.total += foo.baz;
});
于 2012-10-19T23:08:16.480 回答