angular.Array.sum

Description

The sum function calculates the sum of all numbers in an array. If an expression is supplied, sum evaluates each element in the array with the expression and then returns the sum of the calculated values.

Note: This function is used to augment the Array type in Angular expressions. See angular.Array for more info about Angular arrays.

Usage

angular.Array.sum(array[, expression]);

Parameters

Returns

{number}

Sum of items in the array.

Example

 <script>
   function Ctrl() {
     this.invoice = {
       items:[ {
            qty:10,
            description:'gadget',
            cost:9.95
          }
       ]
     };
   }
 </script>
 <table class="invoice" ng:controller="Ctrl">
  <tr><th>Qty</th><th>Description</th><th>Cost</th><th>Total</th><th></th></tr>
  <tr ng:repeat="item in invoice.items">
    <td><input type="integer" ng:model="item.qty" size="4" required></td>
    <td><input type="text" ng:model="item.description"></td>
    <td><input type="number" ng:model="item.cost" required size="6"></td>
    <td>{{item.qty * item.cost | currency}}</td>
    <td>[<a href ng:click="invoice.items.$remove(item)">X</a>]</td>
  </tr>
  <tr>
    <td><a href ng:click="invoice.items.$add({qty:1, cost:0})">add item</a></td>
    <td></td>
    <td>Total:</td>
    <td>{{invoice.items.$sum('qty*cost') | currency}}</td>
  </tr>
 </table>
  //TODO: these specs are lame because I had to work around issues #164 and #167
  it('should initialize and calculate the totals', function() {
    expect(repeater('table.invoice tr', 'item in invoice.items').count()).toBe(3);
    expect(repeater('table.invoice tr', 'item in invoice.items').row(1)).
      toEqual(['$99.50']);
    expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50');
    expect(binding("invoice.items.$sum('qty*cost')")).toBe('$99.50');
  });

  it('should add an entry and recalculate', function() {
    element('.doc-example-live a:contains("add item")').click();
    using('.doc-example-live tr:nth-child(3)').input('item.qty').enter('20');
    using('.doc-example-live tr:nth-child(3)').input('item.cost').enter('100');

    expect(repeater('table.invoice tr', 'item in invoice.items').row(2)).
      toEqual(['$2,000.00']);
    expect(binding("invoice.items.$sum('qty*cost')")).toBe('$2,099.50');
  });