Deborah
Deborah

Reputation: 243

Code for select/unselect all checkboxes in an AngularJS Table

Iam completely confused at a point and need anyone's help here. Went through various examples but nothing could help.

I have a created dynamic table, added with checkboxes. Now whenever a row is selected its id will be bound to an array and it will be diplayed at the top of table.

What I need is:The code for functionality of select all check box. And whenever all the rows are selected by select all checkbox, its ids has to be displayed.

Below is the code for the table:

<table>
<thead>
  <tr>
    <th>
      <input name="all"
      type="checkbox"
      ng-click="selectAll()" />
    </th>
    <th>ID</th>
    <th>Date</th>
  </tr>
</thead>
<tbody ng-repeat="x in cons">
  <tr>
    <td>
      <input type="checkbox" 
      name="selectedids[]"
      value="{{x.id}}"
      ng-checked="idSelection.indexOf(x.id) > -1" 
      ng-click="toggleSelection(x.id, idSelection)"> </td>
    <td>{{x.id}}</td>
    <td>{{x.title}}</td>
  </tr>
</tbody>

app.js:

  $scope.idSelection = [];
$scope.toggleSelection = function toggleSelection(selectionName, listSelection) {

    var idx = listSelection.indexOf(selectionName);
    // is currently selected
    if (idx > -1) {
        listSelection.splice(idx, 1);
    }
        // is newly selected
    else {
        listSelection.push(selectionName);
    }
};


//$scope.selectAll=function(){}
//Need code for this function to work

Here is a demo: http://plnkr.co/edit/m9eQeXRMwzRdfCUi5YpX?p=preview.

Will be grateful, if anyone can guide.

Upvotes: 2

Views: 656

Answers (1)

FuriousD
FuriousD

Reputation: 854

You need a variable to keep track of whether 'All' is currently active or not. If not, we create a new array of all item id's using the array map function, and pass this to idSelection. If allSelected is currently active, we pass an empty array to idSelection

$scope.allSelected = false;

$scope.selectAll = function() {
  $scope.allSelected = !$scope.allSelected;

  if($scope.allSelected) {
    $scope.idSelection = $scope.cons.map(function(item) {
      return item.id;
    });
  } else {
    $scope.idSelection = [];
  }
}

Upvotes: 1

Related Questions