Sari Rahal Sari Rahal - 4 months ago 29
Javascript Question

angular ng-grid selected Items is blank after first iteration

I am working on a bulk action on an ng-grid. When selected all rows the selected items is correct the first time, but after the first bulk action, the selected items is blank. With the code below it sends a notification that "Must select at least 1 row to move." Please let me know if you need any more details. Thanks in advance.

vm.init = function() {
vm.title = "Orphan Entries";
selectReport("OrphanEntries");
};
/* initialization */
vm.init();

vm.gridOptionsReports = {
data: 'vm.data',
multiSelect: true,
enableColumnResize: true,
showFooter: true,
showSelectionCheckbox: true,
enableRowSelection: true,
selectWithCheckboxOnly: true,
selectedItems: [],
selectionCheckboxColumnWidth: 25,
enablePaging: true,
pagingOptions: $scope.pagingOptions
}

$scope.applyBulkAction = function(){
if(vm.selectedAction == 'notset'){
Notification.error("You need to select a bulk action.");
}else{
var rows = vm.gridOptionsReports.selectedItems;
if(rows.length < 1){
Notification.error("Must select at least 1 row to move.");
}else{
var toggleTo = 0;
if(vm.selectedAction == 'move'){
toggleTo = 1;
}
var data = "";
var first =true;
for(var i = 0; i< rows.length; i++){
if(rows[i].selectedToBeMoved != toggleTo){
if(first){
data = '{"ID":"'+rows[i].iD+'"}';
first = false;
}else{
data = data + ',{"ID":"'+rows[i].iD+'"}'
}
}
}
if(data == ""){
Notification.error("The rows that you have selected have already been flagged.")
}else{
return ReportService.flagOrphansToBeMoved(data).then(flagOrphansToBeMovedComplete).catch(flagOrphansToBeMovedFailed);

function flagOrphansToBeMovedComplete(response) {
if(!response.data.error && response.data.status == 200){
Notification.success('Bulk action was successful. All flagged rows will be moved during the next scan.');
//vm.gridOptionsReports.selectedItems = [];
vm.init();
}else{
Notification.error('Error scheduling to move orphan.');
}
return response;
}

function flagOrphansToBeMovedFailed(error) {
Notification.error('Error scheduling to move orphan.');
}
}
}
}
}


UI

enter image description here

UI code:

<div class="row smallPaddingBot">
<div class="col-sm-2">
<select ng-model="vm.selectedAction" class="form-control">
<option value="notset">Bulk Actions</option>
<option value="move">Flag Selected To Be Moved</option>
<option value="dontMove">Flag Selected Not To Moved</option>
</select>
</div>
<div class="col-sm-1">
<button type="button" class="btn btn-default" ng-click="applyBulkAction()">Apply</button>
</div>







Answer

The issue was that I was re-creating the ng-grid every time so I was getting lost in scope. The solution was to set the gridOptionsReports.selectedItems to a scope variable and then reference that scope variable.

From:

selectedItems: [],

To:

selectedItems: vm.selectedRow,

And:

var rows = vm.gridOptionsReports.selectedItems;

To:

var rows = vm.selectedRows;
Comments