Search code examples
javascriptangularjscheckboxangularjs-ng-repeatangularjs-filter

Binding checkbox selections inside ng-repeat table with filter


I'm trying to implement checkboxes for selection of table rows. The table is built with ng-repeat, and I'd like to include a text input to filter the table. When a checkbox is selected, the ID for that item is pushed to an array and it's removed when the box is unchecked. My issue is that after manipulating the filter, the checkboxes do not stay checked. How do I properly bind the checkboxes to my array?

Plunk - https://plnkr.co/edit/U0N3vDTZAULC6CFIdhVp?p=preview

HTML:

    <tr ng-repeat="name in names | filter: search">
      <td>
        <input type="checkbox" class="input-sm" ng-checked="selectedNames.indexOf(name.id) > -1" ng-click="addName(name.id)"/>
      </td>
      <td>{{name.name}}</td>
      <td>{{name.age}}</td>
    </tr>

JS:

  $scope.addName = function (id) {
    var idx = selectedNames.indexOf(id);
    if (selectedNames.indexOf(id) == -1) {
      console.log('Pushing: ', id)
      selectedNames.push(id);
      console.log(selectedNames);
    } else {
      selectedNames.splice(idx,1);
      console.log(selectedNames);
    }

Solution

  • I changed the code a bit, and now it works fine. Here is working plunker. https://plnkr.co/edit/8Jg9hvxibYhVV89Q0bts?p=preview

    This code was added in controller:

      $scope.checkSelected= function(id){
        var idx = selectedNames.indexOf(id);
        return idx > -1;
      }
    

    And I changed your ng-check expression:

    <input type="checkbox" class="input-sm" ng-checked="checkSelected(name.id)" ng-click="addName(name.id)" />