None of the solutions provided worked for me (using ng-grid v2.0.14).
The solution mentioned might work when the data is not extensive or not fetched via an ajax call. Selecting a row "before" ngGridEventData is not feasible because this event is triggered after the rows are rendered. Therefore, if the conditions mentioned are not met or if there is a delay in rendering the grid, the suggested solution may fail.
In my case, I have a grid with around 2000 scrollable rows, and I do not restrict listening to ngGridEventData. I observed that this event is fired four times for me - twice before the data is retrieved from the ajax call and twice after. To handle this behavior, I utilized the jQuery plugin available at to ensure that the function is only called once.
Additionally, the "selectRow/selectItem" function triggers the "afterSelectionChange" event twice, with the first trigger selecting the wrong row for unknown reasons. To address this, I implemented measures to ensure that the event is fired only once and for the correct row.
Here is the sequence of events I experienced:
- ngGridEventData (no afterSelectionChange triggers, likely due to no rendered rows)
- ngGridEventData (no afterSelectionChange triggers, likely due to no rendered rows)
- Ajax call to fetch data
- Delay (possibly for rendering)
- ngGridEventData
- afterSelectionChange x2
- ngGridEventData
- afterSelectionChange x2
To address these issues, I implemented the following:
- Utilized debounce to ensure the function is only called once during the delay, considering the proximity of the calls and checking for rendered rows
- Checked that rendered rows are greater than 0 to avoid triggers on slow systems or connections causing delays in rendering and data loading
- Optionally used rowItem.selected to mitigate issues with afterSelectionChange firing twice, even for row selections
- Implemented the fireOnlyOnce variable to prevent double calling of the afterSelectionChange function
Sample code snippet:
$scope.fireOnlyOnce=true;
$scope.gridOptions = {
//Grid Options Here
afterSelectionChange: function (rowItem) {
if($scope.fireOnlyOnce){
if(rowItem.selected){
//Perform actions
}
} else {
$scope.fireOnlyOnce=true;
}
}
};
$scope.$on('ngGridEventData', jQuery.debounce(100, function (row, event){
var renderedRows = row['targetScope'].renderedRows.length;
if(renderedRows>0){
$scope.fireOnlyOnce=false;
$timeout(function(){$scope.gridOptions.selectRow(2, true)});
}
}));