0

Our team is developing a table widget in ServiceNow and want the ability to select all/ de-select all rows with a checkbox. Our html looks like this so far:

<table class="table table-striped table-responsive" ng-if="data.list.length">
    <thead>
      <tr>
        <th ng-if="options.show_checkboxes">
          <input type="checkbox" ng-click="selectAll()">
        </th> 
        <th ng-repeat="field in data.fields_array track by $index" class="text-nowrap" ng-click="setOrderBy(field)"
         scope="col" role="columnheader" aria-sort="{{field == data.o ? (data.d == 'asc'? 'ascending': 'descending') : 'none'}}">
          <div class="th-title" title="${Sort by} {{field == data.o ? (data.d == 'asc' ?  '${Descending}': '${Ascending}') : '${Ascending}'}}" role="button" tabindex="0" aria-label="{{data.column_labels[field]}}">{{data.column_labels[field]}}</div>
          <i class="fa" ng-if="field == data.o" ng-class="{'asc': 'fa-chevron-up', 'desc': 'fa-chevron-down'}[data.d]"></i>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in data.list track by item.sys_id">
        <td ng-if="options.show_checkboxes">
          <input type="checkbox" ng-model="item.selected">
        </td> 
        <td role="cell" class="pointer sp-list-cell" ng-class="{selected: item.selected}" ng-click="go(item.targetTable, item)" ng-repeat="field in ::data.fields_array" data-field="{{::field}}" data-th="{{::data.column_labels[field]}}"><span ng-if="$first" aria-label="${Open record}: {{::item[field].display_value}}" role="link" tabindex="0">{{::item[field].display_value | limitTo : item[field].limit}}{{::item[field].display_value.length > item[field].limit ? '...' : ''}}</span><span ng-if="!$first">{{::item[field].display_value | limitTo : item[field].limit}}{{::item[field].display_value.length > item[field].limit ? '...' : ''}}</span>
        </td>
      </tr>
    </tbody>
</table>

After seeing some other stackoverflow articles, we added the following into our controller:

$scope.selected = {};
$scope.selectAll = function(){
  for (var i = 0; i < $scope.data.list.length; i++) {
    var item = $scope.data.list[i];

    item.selected = true;
  }
};

The above works to select all, but when a user clicks the checkbox again, the rows are still selected. Is there something that we're missing? Thanks!

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Dave
  • 1,257
  • 2
  • 27
  • 58

1 Answers1

0

Bind the checkbox to a variable with ng-model and use that to select/de-select all:

<input type="checkbox" ng-change="selectAll(allChecked)" ng-model="allChecked">
$scope.selectAll = function(allChecked){
    $scope.data.list.forEach( item => item.selected = allChecked);
};

Then all the items will selected when the checkbox changes to true and de-selected when the checkbox changes to false.

georgeawg
  • 48,608
  • 13
  • 72
  • 95