Hur*_*ile 12 javascript angularjs
我会先说这是对AngularJS很新的,所以请原谅我,如果我的心态远远不够.我正在使用AngularJS编写一个非常简单的单页报告应用程序,肉和土豆当然使用角度模板系统自己生成报告.我有许多报告,我正在从类似Jinja的语法转换,我很难复制任何类型的计数器或运行制表功能.
防爆.
{% set count = 1 %}
{% for i in p %}
{{ count }}
{% set count = count + 1 %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我已经定义了一个变量$scope.total = 0;,然后我可以在模板内部访问而没有问题.我无法弄清楚的是如何total从ng-repeat元素中增加它.我想这会是这样的 -
<ul>
<li ng-repeat="foo in bar">
{{ foo.baz }} - {{ total = total + foo.baz }}
</li>
</ul>
<div> {{ total }} </div>
Run Code Online (Sandbox Code Playgroud)
这显然不起作用,也不会像{{ total + foo.baz}}预先感谢任何建议.
Tim*_*art 33
如果您想要的只是一个计数器(根据您的第一个代码示例),请查看包含ngRepeat中当前(基于0)索引的$ index.然后只显示总数的数组长度.
<ul>
<li ng-repeat="item in items">
Item number: {{$index + 1}}
</li>
</ul>
<div>{{items.length}} Items</div>
Run Code Online (Sandbox Code Playgroud)
如果您想要重复项目中的特定字段,例如价格,则可以使用过滤器执行此操作,如下所示.
<ul>
<li ng-repeat="item in items">
Price: {{item.price}}
</li>
</ul>
<div>Total Price: {{items | totalPrice}}</div>
Run Code Online (Sandbox Code Playgroud)
和过滤功能:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
或者,为了提高可重用性,通用的总过滤功能:
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;
}
});
Run Code Online (Sandbox Code Playgroud)
将使用如下:
<div>Total price: {{items | total:'price'}}</div>
Run Code Online (Sandbox Code Playgroud)
我需要总计而不是那么简单,所以我添加了@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;
};
});
Run Code Online (Sandbox Code Playgroud)
要在列中使用它,您只需:
<div>Total price: {{items | runningTotal:'price':$index}}</div>
Run Code Online (Sandbox Code Playgroud)