ui-grid remove selected row not working - angularjs

When I try to remove selected row in ng-grid the removed rows are still shown in UI.
My grid option is
$scope.gridOptions = {
data: 'myData',
multiSelect: true,
displaySelectionCheckbox: true,
selectedItems: $scope.mySelections,
showFooter: true,
showColumnMenu:false,
showFilter :false,
enableCellEdit: false,
enableCellSelection: false,
enableRowSelection: false,
showSelectionCheckbox: false,
beforeSelectionChange: function() {
return $scope.option.enableRowSelection;
},
}
And I remove or splice the data using
$scope.removeItem=function(){
angular.forEach($scope.mySelections, function(row, index){
angular.forEach($scope.myData, function(data, index){
if(data.indexno == row.indexno){
$scope.myData.splice(index,1);
$scope.gridOptions.data = 'myData';
console.log("after",$scope.myData);
console.log("after data",$scope.gridOptions.data);
}
});
});
$(".badge").html($scope.mySelections.length);
}
Any suggestions or solutions please

The way I have removed a row is by only allowing the user to select 1 row at a time but you could make it so that everything the user selects gets removed. this is the line of code that I used to actually do the removing
$scope.GridOptions.data.splice($scope.GridApi.grid.renderContainers.body.visibleRowCache.indexOf($scope.selectedRow), 1);
But here is how I did it. Here is my grid options at the top of my controller with a var that holds the selected row. you could make this an array of selected rows however!
$scope.selectedRow = null;
$scope.GridOptions = {
enableSorting: true,
enableRowSelection: true,
enableRowHeaderSelection: false,
enableColumnResizing: true,
columnDefs: [
{ name:'User Name', field: 'username', width: '15%', minWidth: 100},
{ name:'Dependency Key', field: 'id', width: '20%', minWidth: 100},
{ name:'Dependency File', field: 'file', width: '30%', minWidth: 100},
{ name:'Modified By', field: 'modifiedBy', width: '15%', minWidth: 100},
{ name:'Modified On', field: 'modifiedOn', width: '10%', minWidth: 100, cellTemplate:'<div class="ui-grid-cell-contents">{{grid.appScope.convertDate(row.entity.modifiedOn)}}</div>'},
{ name:'Dep. File Checksum', field: 'checksumAmericas', width: '10%', minWidth: 100}
],
onRegisterApi : function(gridApi) {
$scope.GridApi = gridApi;
}
};
$scope.GridOptions.multiSelect = false;
then this method gets called each time the user clicks on a row. I get which row the user has selected and assigned it to $scope.selectedRow
$scope.GridOptions.onRegisterApi = function(gridApi){
//set gridApi on scope
$scope.GridApi = gridApi;
$scope.GridApi.selection.on.rowSelectionChanged($scope,function(row){
if($scope.selectedRow == null)//user has not selected a row
$scope.selectedRow = row;
else if(row.entity.username == $scope.selectedRow.entity.username && row.entity.id == $scope.selectedRow.entity.id)//user clicked the same row that was selected and now has unselected
$scope.selectedRow = null;
else //user selected new row
$scope.selectedRow = row;
});
};
Then to when the user clicks remove button it calls a method and inside that method i check to see if $scope.selectedRow is not null and then to remove from the table is just 1 line
if($scope.selectedRow != null)
$scope.GridOptions.data.splice($scope.GridApi.grid.renderContainers.body.visibleRowCache.indexOf($scope.selectedRow), 1);
This website really helps with ui-grid functionality:
http://ui-grid.info/
http://ui-grid.info/docs/#/tutorial/210_selection
Hope this helps

Related

Angular ui-grid disable cell focus for row selection checkboxes

I have a ui-grid with several columns. Two of those columns are editable. I have also enabled row selection which makes the checkboxes appear in the left most column of the row.
I have disabled cell focus for non-editable columns. What I want to achieve is when I edit one of the editable column cell and hit tab, it should navigate only between the editable columns. The problem with the current setup is that the focus shifts from the editable cells in a row to the selection checkbox in the next row instead of going to next editable cell. I want to disable focus for the selection checkboxes.
vm.tableOptions = {
appScopeProvider: vm,
data: [],
enableSorting: true,
enableFiltering: true,
enableRowSelection: true,
enableColumnResizing: true,
enableSelectAll: true,
multiSelect: true,
enableGridMenu: true,
virtualizationThreshold: 18,
fastWatch: true,
scrollDebounce: 500,
wheelScrollThrottle: 500,
rowHeight: 40,
headerRowHeight: 40,
minRowsToShow: 15,
paginationPageSize: 25,
paginationPageSizes: [],
treeRowHeaderAlwaysVisible: false,
saveScroll: true,
saveGroupingExpandedStates: true,
enableCellEditOnFocus: true,
onRegisterApi: function (gridApi) {
vm.gridApi = gridApi;
/**
* Checks if any rows are selected in the tasks grid.
* #returns True if any tasks are selected; otherwise, false.
*/
function anyRowsSelected() {
var selectedRows = vm.gridApi.selection.getSelectedRows();
return selectedRows ? selectedRows.length > 0 : false;
};
// Check if any tasks are selected when the selection changes
gridApi.selection.on.rowSelectionChanged(null, function (row) {
vm.isRowsSelected = anyRowsSelected();
});
// Check if any tasks are selected when batch selection changes
gridApi.selection.on.rowSelectionChangedBatch(null, function (rows) {
vm.isRowsSelected = anyRowsSelected();
});
// This is a hack to manually move the focus to next editable cell
// I want to avoid this since this is causing some issues.
gridApi.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) {
var assetColIndex = 4;
if (newRowCol.col.name === "selectionRowHeaderCol" &&
oldRowCol.col.name === "SerialNumber") {
vm.gridApi.cellNav.scrollToFocus(newRowCol.row.entity, vm.tableOptions.columnDefs[assetColIndex]);
}
});
$timeout(vm.restoreGridState, 50);
},
columnDefs: [
{ name: "DiscreteSkuId", enableCellEdit: false, allowCellFocus: false },
{
name: "SlotBin",
cellTemplate: slotBinCellTemplate,
enableCellEdit: false,
allowCellFocus: false,
sort: {
direction: 'desc',
priority: 0
}
},
{ name: "Model", enableCellEdit: false, allowCellFocus: false },
{ name: "AssetType", enableCellEdit: false, allowCellFocus: false },
{ name: "AssetTag" , cellTemplate: editableCellTemplate, cellEditableCondition: allowTableEdit },
{ name: "SerialNumber" , cellTemplate: editableCellTemplate, cellEditableCondition: allowTableEdit },
{ name: "ValidationFailureReasons", cellTemplate: errorMessageCellTemplate, enableCellEdit: false, allowCellFocus: false }
]
};
This is in the html page.
<div id="table" ui-grid="rackItemDetailsCtrl.tableOptions" ng-disabled="rackItemDetailsCtrl.disableUserInteraction" class="grid tasks-table ui-grid-row-hover" ui-grid-save-state ui-grid-resize-columns ui-grid-selection ui-grid-grouping ui-grid-move-columns ui-grid-auto-resize ui-grid-scrolling-fix ui-grid-edit ui-grid-cellNav></div>
Angular ui-grid version: 3.1.0.1
Angularjs version: 1.4.9
You can disable cell focus on a column with the allowCellFocus flag. However, the row selection column is created automatically and you have no way to set this flag. The solution to to manually access the column after it is created and set allowCellFocus to false. Here is how you can do that:
gridApi.grid.getColumn('selectionRowHeaderCol').colDef.allowCellFocus = false;

Updating cell data in ui-grid without page refresh

I have a table that I made using ui-grid. The table displays information about a list of news stories. In the final column, I am giving the user the ability to edit, delete, and/or make a news story.
Everything seems to be working fine with that - I am able to have a modal pop up, and after entering in the required information, I can see my data change on the server. If I refresh the page, I can also see my data change on the table. However, I would like the cell data to change without page refresh. It doesn't seem to be binding to my news data.
Here is the ui-grid:
$scope.news = getAdminNews.results;
/**
* ui-grid implementation
*/
$scope.gridOptions = {
data: 'news',
enableColumnResizing: true,
enableFiltering: true,
enableGridMenu: false,
enableColumnMenus: false,
paginationPageSizes: [25,50,75],
paginationPageSize: 25,
rowHeight: 75
};
$scope.gridOptions.columnDefs = [{
displayName: 'Title',
field: 'title.rendered',
filterCellFiltered: true,
sortCellFiltered: true,
width: '20%'
}, {
displayName: 'Body',
field: 'body',
width: '20%'
}, {
displayName: 'Created',
field: 'created',
type: 'date',
cellFilter: 'date:"yyyy-MM-dd"',
filterCellFiltered: true,
sortCellFiltered: true,
width: '20%',
sort: {
priority: 0
}
},
{
displayName: 'Actions',
displayName: 'Actions',
width: '20%',
enableSorting: false,
enableFiltering: false,
field: 'actions',
cellTemplate: 'table-cell-actions'
}
];
$scope.gridOptions.onRegisterApi = function(gridApi) {
$scope.gridApi = gridApi;
};
And one part of my controller which is working successfully:
$scope.newPost = function() {
ngDialog.openConfirm({
template: 'modalPostNew',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function() {
var newPost = {
"id": 0,
"title": $scope.newPostForm.title
}
AdminNews.save(newPost);
toaster.pop('success', 'Updated', 'News item updated successfully.');
});
}
I needed to update my $scope.news data that ui-grid was populating the table with. Here is what my controller looks like now:
$scope.newPost = function() {
ngDialog.openConfirm({
template: 'modalPostNew',
className: 'ngdialog-theme-default',
scope: $scope
}).then(function() {
var newPost = {
"id": 0,
"title": $scope.newPostForm.title
}
AdminNews.save(newPost).$promise.then(function(response) {
var myObj = {
"id": response.data.id,
"title": {
"rendered": response.data.title
}
}
$scope.news.push(myObj);
});
toaster.pop('success', 'Updated', 'News item updated successfully.');
});
}

angular ui-grid disable edit for view mode

is there a way to disable/enable cell edit of the grid. for example i have a master-detail form screen. when user wants to analyze a record, i disable all controls of the form with ng-disabled. but i could not prevent editing the grid. i tried "cellEditableCondition" option. But, i runs only when grid is loading. it would be nice if grid have an option like "disableEdit" and accepts a scope variable. when i open my form in edit mode, grid would be editable, and when in view mode grid would be disabled.
i found a solution. you can use cellEditableCondition attribute of the grid column. if you apply a function to this attribute, you can enable/disable dynamically cells. here is a plunker:
$scope.canEdit = function () { return $scope.pageOptions.isView; };
$scope.pageOptions = { isView : false};
$scope.gridOptions1 = {
enableRowSelection: true,
enableSelectAll: true,
enableFiltering: true,
columnDefs: [
{ name: 'name', width: '30%',cellEditableCondition: $scope.canEdit },
{ name: 'gender', width: '20%',cellEditableCondition: $scope.canEdit },
{ name: 'age', width: '20%',cellEditableCondition: $scope.canEdit },
{ name: 'company', width: '25%',cellEditableCondition: $scope.canEdit },
{ name: 'state', width: '35%',cellEditableCondition: $scope.canEdit },
{ name: 'balance', width: '25%',cellEditableCondition: $scope.canEdit }
],
isRowSelectable:function(row){if(row.entity['age']>30) return true; return false;},
onRegisterApi: function( gridApi ) {
$scope.gridApi = gridApi;
}
};
http://plnkr.co/edit/md9AOA64Zn67KqhNmhZT?p=preview

ng-grid paging: total items and page count is wrong

I have followed several threads in here related to the issue but couldn't find the issue with my code. I have a paged ng-grid, but the total item count (bottom left corner) and the total page count x/n is wrong. When I should have 14 as total items and 3 as total pages for a page size of 5, I see the total count as 5 and the total pages as 1. However, I can navigate to the other pages with the arrow icon.
Here is my code:
vm.gridOptions = {
data: "vm.pagedDataList",
rowHeight: 35,
enableCellSelection: false,
enableRowSelection: true,
multiSelect: false,
columnDefs: [
{ field: 'locationId', displayName: localize.getLocalizedString('_LocationCode_'), visible: false},
{ field: 'locationCode', displayName: localize.getLocalizedString('_LocationCode_'), width: '10%', cellTemplate: tooltipTemplateUrl },
{ field: 'locationTypeName', displayName: localize.getLocalizedString('_Locationtype_'), width: '15%', cellTemplate: tooltipTemplateUrl },
{ field: 'locationName', displayName: localize.getLocalizedString('_LocationName_'), width: '15%', cellTemplate: tooltipTemplateUrl },
{ field: 'locationDisplayName', displayName: localize.getLocalizedString('_LocationDisplayName_'), width: '15%', cellTemplate: tooltipTemplateUrl }
],
enablePaging: true,
showFooter: true,
pagingOptions: { pageSizes: [5,10], pageSize: 5, currentPage: 1 },
totalServerItems: 'vm.locationList.length'
};
$scope.$watch('vm.gridOptions.pagingOptions', function (newVal, oldVal) {
//if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
vm.getPagedDataAsync(vm.gridOptions.pagingOptions.pageSize, vm.gridOptions.pagingOptions.currentPage, null);
//}
}, true);
vm.setPagingData = function (data, page, pageSize) {
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
vm.pagedDataList = pagedData;
vm.gridOptions.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
vm.getPagedDataAsync = function (pageSize, page) {
vm.setPagingData(vm.locationList, page, pageSize);
};
Then I call this in the init() method, after the data is loaded;
vm.getPagedDataAsync(vm.gridOptions.pagingOptions.pageSize, vm.gridOptions.pagingOptions.currentPage);
change line
totalServerItems: 'vm.locationList.length'
to
totalServerItems: 'totalServerItems',
and
vm.gridOptions.totalServerItems = data.length;
to
$scope.totalServerItems = data.length;

EXT Grid with multiple checkboxes - Selecting item deselects another

I have a EXT JS 4.2 grid 5 columns, it has the normal selection checkbox at the far left along with an additional checkbox in the second to last column and a radio in the last column.
If I click and select a row in the selection column then go to click the 'Primary' radio or 'Full' checkbox it will unselect whatever is already selected on that row. For instance, if I select row 1 then go to click the Primary Radio it will unselect, then if I click on Full it will deselect the Radio. Then If click on the Radio again and then Full they will stay selected.
It seems like once the checkbox or radio are selected a second time it begins to act normally, not sure why this behaviour is occuring or how to correct it.
I have tried adding the checkOnly: true paramater but that did not seem to do anything different.
Here is the code for the Grid:
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.selection.CheckboxModel'
]);
Ext.onReady(function(){
Ext.QuickTips.init();
// Data store
var data = Ext.create('Ext.data.JsonStore', {
autoLoad: true,
fields: [ 'name', 'market', 'expertise', 'id', 'isFull', 'isPrimary'],
proxy: {
type: 'ajax',
url: '/opsLibrary/getLibraryJson'
}
});
// Selection model
var selModel = Ext.create('Ext.selection.CheckboxModel', {
columns: [
{xtype : 'checkcolumn', text : 'Active', dataIndex : 'id'}
],
checkOnly: true,
mode: 'multi',
enableKeyNav: false,
listeners: {
selectionchange: function(value, meta, record, row, rowIndex, colIndex){
var selectedRecords = grid4.getSelectionModel().getSelection();
var selectedParams = [];
// Clear input and reset vars
$('#selected-libraries').empty();
var record = null;
var isFull = null;
var isPrimary = null;
// Loop through selected records
for(var i = 0, len = selectedRecords.length; i < len; i++){
record = selectedRecords[i];
// Is full library checked?
isFull = record.get('isFull');
// Is this primary library?
isPrimary = record.get('isPrimary');
// Build data object
selectedParams.push({
id: record.getId(),
full: isFull,
primary: isPrimary
});
}
// JSON encode object and set hidden input
$('#selected-libraries').val(JSON.stringify(selectedParams));
console.log(JSON.stringify(selectedParams));
}}
});
// Render library grid
var grid4 = Ext.create('Ext.grid.Panel', {
xtype: 'gridpanel',
id:'button-grid',
store: data,
forceSelection : false,
autocomplete: false,
typeAhead: false,
columns: [
{text: "Library", width: 170, sortable: true, dataIndex: 'name'},
{text: "Market", width: 125, sortable: true, dataIndex: 'market'},
{text: "Expertise", width: 125, sortable: true, dataIndex: 'expertise'},
{text: 'Full', dataIndex:'isFull', checkOnly: true, width: 72,
renderer: function (value, meta, record) {
return '<center><input type="checkbox" onclick="var s = Ext.getCmp(\'button-grid\').store; s.getAt(s.findExact(\'id\',\'' + record.get('id') + '\')).set(\'isFull\', this.value)"'
}},
{text: 'Primary', dataIndex:'isPrimary', checkOnly: true, width: 72,
renderer: function(value, meta, record)
{
return '<center><input type="radio" onclick="var s = Ext.getCmp(\'button-grid\').store; s.getAt(s.findExact(\'id\',\'' + record.get('id') + '\')).set(\'isPrimary\', this.value)"'
}},
],
columnLines: false,
selModel: selModel,
width: 600,
height: 300,
frame: true,
title: 'Available Libraries',
iconCls: 'icon-grid',
renderTo: Ext.get('library-grid')
});
});
Any help would be greatly appreciated....
Thanks!
I think problem is that your render functions for checkbox and radio columns are not bound to the state of your model, and each time they are rendered the boxes are shown as unchecked.
Try to add 'checked' attribute to your boxes in render functions if value in model is true e.g.:
return '<center><input type="checkbox" ' + (value ? 'checked' : '') + ' onclick=.....
This should bring consistency to the functionality at least.

Categories

Resources