Increment A Variable In AngularJS Template

前端 未结 3 1251
广开言路
广开言路 2020-12-16 16:19

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, th

相关标签:
3条回答
  • 2020-12-16 16:31

    I'm not sure I totally understand the question, but are just needing to display the total number in the object you're iterating over? Just set $scope.total to the length of your array (bar in your example above). So, $scope.total = $scope.bar.length;

    If you're wanting the total of all the foo.baz properties, you just need to calculate that in your controller.

    $scope.total = 0;
    angular.forEach($scope.bar, function(foo) {
        $scope.total += foo.baz;
    });
    
    0 讨论(0)
  • 2020-12-16 16:45

    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>
    
    0 讨论(0)
  • 2020-12-16 16:49

    I needed running total rather that plain total, so I've added upon what @TimStewart left. Here the code:

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

    To use it in column you just do:

    <div>Total price: {{items | runningTotal:'price':$index}}</div>
    
    0 讨论(0)
提交回复
热议问题