Rohan Kangale
Rohan Kangale

Reputation: 971

UI grid get selected row's index

I want the index/index value of the selected row, in ui-grid. I tried to get it using the onRowSelectionChange event, but I wasn't able to.

What can I do to obtain the selected row's index?

Upvotes: 0

Views: 13462

Answers (2)

Vikki
Vikki

Reputation: 181

In controller grid_options set:

onRegisterApi: function(gridApi) {
                $scope.gridApi = gridApi;
                gridApi.selection.on.rowSelectionChanged($scope,function(row){
                 var removeRowIndex = $scope.grid_Options.data.indexOf(row.entity);
                });
               }

$scope.grid_Options.data is actually data which you provided to grid.

Upvotes: 3

S. Baggy
S. Baggy

Reputation: 958

There may be a more elegant solution these days, but in the version of ui-grid I was working with some months ago, I used the following service function to get the row index.

getRowIndex: function (row, grid) {
    var rowIndex = -1;
    for (var i = 0; i < grid.renderContainers.body.visibleRowCache.length; i++) {
        if (row.uid === grid.renderContainers.body.visibleRowCache[i].uid) {
            rowIndex = i;
            break;
        }
    }
    return rowIndex;
}

You can get the reference to the row from many events, including the rowSelectionChanged event.

To get the reference to the grid...

$scope.gridOptions.onRegisterApi = function (gridApi) {
    $scope.gridApi = gridApi;
}

And call

var myIndex = myService.getRowIndex(row, $scope.gridApi.grid);

Note that this index changes when you re-sort or change the data. It is based on the index of the data as the user sees it.

Upvotes: 4

Related Questions