Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngGrid multiselect canceling current selection

I would like to configure ng-grid to obtain the following multi selection behaviour:

  1. Selecting a single row cancels the previous selection

  2. Selecting with Ctrl or Shift adds to current selection (like selecting files in windows explorer for example)

Details:

  • if I select a row, the whole row is selected (enableRowSelection)
  • if I select a row holding Ctrl the new row is selected in addition to the currently selected rows
  • if I select holding Shift the range is selected
  • if I select a row without pressing any key I would like the row to be selected and the others unselected

ng-grid works as expected except for the last step (unselecting the other rows when clicking a row)

like image 664
mabi Avatar asked Oct 16 '13 17:10

mabi


1 Answers

You can add this to your grid's controller:

$scope.multiSelect = false;
// control/shift/meta keydown enables multiselect
$('.your-grid').keydown(function (e) {
    if ((e.keyCode === 16 || e.keyCode === 17 || e.metaKey || e.keyCode === 224 || e.keyCode === 91 || e.keyCode === 93) && !$scope.multiSelect) {
        $scope.multiSelect = true;
    }
});
// keyup disables it
$('.your-grid').keyup(function (e) {
    if (e.keyCode === 16 || e.keyCode === 17 || e.metaKey || e.keyCode === 224 || e.keyCode === 91 || e.keyCode === 93) {
        $scope.multiSelect = false;
    }
});

$scope.gridOptions.beforeSelectionChange = function () {
    // if the shift/ctrl/meta keys aren't pressed, then each selection
    // will clear all the previous ones
    if (!$scope.multiSelect) {
        for (var i = 0; i < $scope.gridOptions.data.length; ++i) {
            $scope.gridOptions.selectRow(i, false);
        }
    }
    return true;
};

Where your view would look something like:

<div class="your-grid" ng-grid="gridOptions">

The reason for all of the different keyCode values is that Mac's command key's keycode is browser dependant. You can use e.metaKey, but that doesn't work for everything (Mac's Chrome does not I believe). So to be safe you can check all of those keyCode values which are described in the SO post: How does one capture a Mac's command key via JavaScript?

This solution is inspired by: AngularJS Change multiple row selection ng-grid attribute on key down and another SO post that I can't find at the moment.

like image 68
jCuga Avatar answered Nov 06 '22 21:11

jCuga