Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Increment A Variable In AngularJS Template

I'll preface this by saying I am very new to AngularJS so forgive me if my mindset is far off base. I am writing a very simple single page reporting app using AngularJS, the meat and potatoes is of course using the angular templating system to generate the reports themselves. I have many many reports that I am converting over from a Jinja-like syntax and I'm having a hard time replicating any kind of counter or running tabulation functionality.

Ex.

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

In my controller I have defined a variable like $scope.total = 0; which I am then able to access inside of the template without issue. What I can't quite figure out is how to increment this total from within an ng-repeat element. I would imagine this would look something like -

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

This obviously doesn't work, nor does something like {{ total + foo.baz}}, thanks in advance for any advice.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If all you want is a counter (as per your first code example), take a look at $index which contains the current (0 based) index within the containing ngRepeat. And then just display the array length for the total.

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

If you want a total of a particular field in your repeated items, say price, you could do this with a filter, as follows.

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

And the filter function:

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

Or, for improved reusability, a generic total filter function:

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

Which would be used like:

<div>Total price: {{items | total:'price'}}</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...