Search code examples
angularjsangularjs-ng-repeatangular-ngmodel

Update Totals in ng-repeat


Please take a look at this fiddle

What I'm trying to do is to calculate/update totals for each column inside a nested ng-repeat:

 <tr ng-repeat="cust in customers">
     <td>{{cust.name}}</td>
     <td ng-repeat="book in books">
         <p ng-init="index=getIndex(book.id, cust.id)"></p>
         <input ng-model="qtys[index].qty">
     </td>
 </tr>
 <tr>
     <td>Total</td>
     <td ng-repeat="book in books">
         <input type=text value="{{sumQty(book.id)}}">
     </td>
 </tr>

I have 2 problems that I'm trying to solve:

  1. The input boxes are now showing the correct values from my array. I'm trying to use ng-init to get the index from the array first based on the custId and bookId I pass in:

     <p ng-init="index=getIndex(book.id, cust.id)"</p>
     <input ng-model="qtys[index].qty">
    

    I guess I'm not sure how to correctly bind the ng-model

  2. The totals are not working. But I guess I need to solve the #1 problem before I can get this to work.

Please help. Thanks.


Solution

  • You got it almost right. The problem is in your getIndex method - the return that you do there does not return from getIndex, it just exits the function that you passed to forEach. If you modify it like this, it will work

    $scope.getIndex = function(bookId, custId) {
        var index = null;
        angular.forEach($scope.qtys , function(item, idx) {
            if (item.bookId == bookId && item.custId == custId) {
                index = idx;
            };
        });
        return index;
    };
    

    scope.sumQty seems unfinished (it takes a list as parameter, but you are passing an id to it). One way of fixing it would be to make it accept the id instead

    $scope.sumQty = function(id) {
      var total=0;
      angular.forEach($scope.qtys , function(item){
          if(item.bookId == id) {
            total+= parseInt(item.qty);
          }
      });
      return total;
    }