Search code examples
angularjsangularjs-ng-repeat

Angularjs ng-repeat query filter clears user-input values


saleItems = [
  {
    "id": 236,
    "variant": "Oval Holder",
    "mrp": "66.00"
  },
  {
    "id": 237,
    "variant": "Angle Holder",
    "mrp": "52.00"
  }
]

my template looks like:

<input ng-model="$ctrl.query" />
<table>
  <tr><th>Sale Invoice</th></tr>
  <tr>
    <th>No.</th>
    <th>Item.</th>
    <th>Quantity</th>
    <th>Rate</th>
    <th>Discount</th>
    <th>Discount Amount</th>
    <th>Total Amount</th>
  </tr>
  <tr ng-repeat="item in $ctrl.saleItems | filter:$ctrl.query | orderBy:$ctrl.orderProp">
    <td ng-init="item.total_amount=0;item.sale_quantity =0">{{$index + 1}}</a></td>
    <td>{{item.variant}}</td>
    <td><input type="text" value="{{item.sale_quantity}}"></td>
    <td class='amt'>{{item.mrp | currency : "₹" : 2}}</td>
    <td class='amt' >{{item.total_amount | currency : "₹" : 2}}</td>
  </tr>
  <tr><td>{{$ctrl.sale_total_amount()}}</td></tr>
</table>

As you can see from the above template, there is an input field for item.sale_quantity. But with $ctrl.query filter on ng-repeat, if I search an item, the rows are filtered. But when the query filter is cleared, the user inputted data on the unfiltered rows is lost. How to retain the inputted data on all rows regardless of whether filtered or not?


Solution

  • you have the following init statement that clears the values of total and quantity everytime this column is rendered.

    <td ng-init="item.total_amount=0;item.sale_quantity =0">{{$index + 1}}</a></td>
    

    I suggest initialize your array inside your controller once when data is loaded using a for loop.

    angular.forEach($scope.saleItems, function(value, key){
      value.total_amount = 0;
      value.sale_quantity  = 0;
    });