【问题标题】:Increment A Variable In AngularJS Template在 AngularJS 模板中增加一个变量
【发布时间】:2014-06-25 04:42:45
【问题描述】:

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

例如

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

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

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

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

【问题讨论】:

  • 加法运算符不明确,但减法强制类型转换为数字。 {{count - -1}}

标签: javascript angularjs


【解决方案1】:

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

<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;
  }
});

或者,为了提高可重用性,一个通用的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>

【讨论】:

  • 第二个例子正是我要找的!非常感谢。
  • 对于通用的总过滤器函数,该字段应该是返回函数的参数,而不是过滤器本身(否则 Angular 会抱怨它是一个未知的 Provider),即 app.filter("total", function() {return function(items, field) {
【解决方案2】:

我需要运行总计而不是简单的总计,所以我添加了 @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>

【讨论】:

  • 非常优雅的总计运行解决方案
【解决方案3】:

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

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

$scope.total = 0;
angular.forEach($scope.bar, function(foo) {
    $scope.total += foo.baz;
});

【讨论】:

  • 从报告的角度来看,这并没有多大意义。在处理模板之前对报表数据中的所有总计进行预处理在许多情况下实际上是不可能的。
猜你喜欢
  • 2011-01-31
  • 1970-01-01
  • 2019-08-07
  • 2011-11-05
  • 2019-06-08
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多