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

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;

Related

populate Dropdownlist in ui grid dynamically

i have spent lots of hours finding a solution but no success every time i am finding a solution it ends up with static data not from any web API or database. i want dynamic data to be populated in drop down list in UI grid. i have read in one blog in which guy was saying for dynamic data we have to use editDropdownRowEntityOptionsArrayPath but i did not find any useful solution. any one can provide any useful information than i will be vary thankful. thanks in advance. this is what i have done.
$scope.listOptions = []; $scope.ddlist = [];
$http.get('http://localhost:26413/api/MenuVDN/GetVDNList')
.then(function (data) {
$scope.listOptions = data;
$scope.ddlist = $scope.listOptions.data.Table;
console.log($scope.ddlist);
})
$scope.gridOptions = {
enableColumnResizing: true,
enableSorting: true,
enableCellSelection: true,
canSelectRows: true,
// enableCellEdit: true,
columnDefs: [
{ field: 'NameEn', displayName: ' Menu Name', grouping: { groupPriority: 0 }, sort: { priority: 0, direction: 'asc' }, width: '25%' },
{ field: 'id', displayName: 'ID' },
{ field: 'language', displayName: 'VDN Language', grouping: { groupPriority: 1 }, sort: { priority: 1, direction: 'asc' } },
{ field: 'vdnname', displayName: 'VDN Name' },
{
field: 'vdnnum', displayName: 'VDN Number',
editableCellTemplate: 'ui-grid/dropdownEditor',
// editDropdownIdLabel: 'id',
editDropdownValueLabel: 'value',
// enableFocusedCellEdit: true,
enableCellEditOnFocus :true,
enableCellEdit: true,
editType: 'dropdown',
editDropdownRowEntityOptionsArrayPath : $scope.ddlist
// , cellEditableCondition: function( $scope ) { return true; }
}
]
};
plus i am getting response from webapi in json format like this.
{"Table":[{"id":2,"value":"AR-BOOKING-NEW (7101)"},
{"id":3,"value":"EN-BOOKIN-NEW (7102)"},
{"id":4,"value":"AR-BOOKING-CANCEL (7103)"},
{"id":5,"value":"EN-BOOKING-CANCEL (7104)"},
{"id":6,"value":"AR-BOOKING-MODIFY (7105)"}]}
$scope.columns = completedFiles.columns;
$scope.rows = completedFiles.rows;
//prepare custom column for ui-grid
var customColumns = [];
angular.forEach($scope.columns, function(column) {
customColumns.push({
field : column.fieldName,
displayName : column.displayName,
editable : column.editable,
dataType : column.dataType,
});
}
});
angular.forEach(customColumns, function(customColumn) {
customColumn['width'] = 200;
if (customColumn.dataType === 'dropDown') {
customColumn['cellTemplate'] = "<div class='ui-grid-cell-contents' id='col-description'><select class="form-control" data-ng-options="item in grid.appScope.arrayName track by item" ><option value="" selected hidden />/></select></div>";
customColumn['width'] = 180;
}
});
You can create custom template like above and after that just assign in $scope.gridOptions customColumns to columnDefs rather then defining the column definition there.

using expandable Angular js ui grid

I am using Expandable UI Grid.
My data is shown in grid which is expanded on click and grid is refreshed every 5 secs.
If I expand a row then it is collapsed every 5 seconds as the grid refreshes.
How can I maintain the row expansion when the grid refreshes?
Code
$scope.fillProductList = function () {
$http({
method: 'GET',
url: getJobs,
data: {}
}).success(function (result) {
$scope.showSubListGrid = false;
$scope.myData = '';
var gridDataWithDownload = result;
//grid data
$scope.myData = gridDataWithDownload;
$scope.gridOptionsCategory.data = gridDataWithDownload;
// $scope.refresh = false;
timer = $timeout(function () {
$scope.fillProductList();
}, timeOutStamp);
}).error(function (result) {
timer = $timeout(function () {
$scope.fillProductList();
}, timeOutStamp);
});
};
$scope.gridOptionsCategory = {
useExternalPagination: true,
expandableRowHeight: 300,
enableSorting: true,
data: $scope.myData,
enableColumnResizing: true,
enableGridMenu: false,
expandableRowTemplate: 'griddata.html',
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
// gridApi.expandable.toggleRowExpansion($scope.gridApi.grid.row[0].entity);
gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
$scope.gridApi.grid.modifyRows($scope.gridOptionsCategory.data);
$scope.gridApi.selection.selectRow($scope.gridOptionsCategory
.data[0]);
//$scope.gridOptionsCategory.expandableRowHeight = 500;
//$timeout.cancel(timer);
if (row.isExpanded) {
row.entity.components = JSON.parse(row.entity.components)
this.scope.gridOptionsCategory.expandableRowScope = row.entity;
// $scope.GridOptions.expandableRowScope = row.entity.components;
}
if (!row.isExpanded) {
timer = $timeout(function () {
$scope.fillProductList();
}, timeOutStamp);
}
});
},
enableHorizontalScrollbar: 0,
//enableVerticalScrollbar:0,
//useExternalSorting: true,
columnDefs: [{
field: 'filtertoggle',
displayName: '',
visible: true,
headerCellTemplate: '' +
'<button id=\'toggleFiltering\' style= "padding:3px 7px;" ng-click="grid.appScope.toggleFiltering()" class="btn btn-warning glyphicon glyphicon-filter">' +
'</button>'
},
{
name: 'Job Name',
field: 'name',
width: '20%',
enableCellEdit: false,
enableHiding: true,
enableGrouping: false,
// enableFiltering: true,
filter: {
term: $scope.filterOptions.filterText
}
},
{
name: 'Profile',
field: 'profile',
width: '15%',
enableCellEdit: false,
enableHiding: true,
enableGrouping: false
}, {
name: 'Progress',
field: 'progress',
enableSorting: true,
width: '18%',
enableCellEdit: false,
enableHiding: true,
enableGrouping: false,
// enableFiltering: true,
cellTemplate: statusTemplate
}
]
};
gridApi.core.on.rowsRendered(scope,() => {
if (!gridApi.grid.expandable.expandedAll && !initialized)
{ gridApi.expandable.expandAllRows();
initialized = true;
}
});
Can you check with these code. You might get some idea.

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.');
});
}

ExtJS Paging toolbar with an ability to select items count per page

Im using ExtJS 4.2 Ext.toolbar.Paging and I want to have an ability to select items count on a page, ie set pageSize of a store.
My solution is to extend existing Ext.toolbar.Paging, but maybe there is much easier solution? Or my solution can be improved?
Solution:
Ext.require([
'Ext.toolbar.Paging'
]);
Ext.define('Ext.lib.extensions.PortalPagingToolbar', {
extend: 'Ext.toolbar.Paging',
alias: 'widget.portalPagingToolbar',
alternateClassName: 'Portal.PagingToolbar',
/**
* Objects per page default
*/
objectsPerPageDefault: 25,
/**
* Objects per page text
*/
objectsPerPageText: 'Objects per page:',
/**
* Gets the paging items in the toolbar
* #private
*/
getPagingItems: function () {
var me = this;
return [
{
itemId: 'first',
tooltip: me.firstText,
overflowText: me.firstText,
iconCls: Ext.baseCSSPrefix + 'tbar-page-first',
disabled: true,
handler: me.moveFirst,
scope: me
},
{
itemId: 'prev',
tooltip: me.prevText,
overflowText: me.prevText,
iconCls: Ext.baseCSSPrefix + 'tbar-page-prev',
disabled: true,
handler: me.movePrevious,
scope: me
},
'-',
me.beforePageText,
{
xtype: 'numberfield',
itemId: 'inputItem',
name: 'inputItem',
cls: Ext.baseCSSPrefix + 'tbar-page-number',
allowDecimals: false,
minValue: 1,
hideTrigger: true,
enableKeyEvents: true,
keyNavEnabled: false,
selectOnFocus: true,
submitValue: false,
// mark it as not a field so the form will not catch it when getting fields
isFormField: false,
width: me.inputItemWidth,
listeners: {
scope: me,
keydown: me.onPagingKeyDown,
blur: me.onPagingBlur
}
},
{
xtype: 'tbtext',
itemId: 'afterTextItem',
text: Ext.String.format(me.afterPageText, 1)
},
'-',
{
itemId: 'next',
tooltip: me.nextText,
overflowText: me.nextText,
iconCls: Ext.baseCSSPrefix + 'tbar-page-next',
disabled: true,
handler: me.moveNext,
scope: me
},
{
itemId: 'last',
tooltip: me.lastText,
overflowText: me.lastText,
iconCls: Ext.baseCSSPrefix + 'tbar-page-last',
disabled: true,
handler: me.moveLast,
scope: me
},
'-',
{
xtype: 'tbtext',
itemId: 'objectsPerPageText',
text: Ext.String.format(me.objectsPerPageText, 1)
},
{
xtype: 'combo',
isFormField: false,
itemId: 'comboItemsCount',
name: 'comboItemsCount',
store: [
['10', '10'],
['25', '25'],
['50', '50'],
['100', '100'],
['250', '250'],
['500', '500'],
['1000', '1000']
],
width: 75,
listeners: {
scope: me,
change: me.onItemsPerPageChange
}
},
'-',
{
itemId: 'refresh',
tooltip: me.refreshText,
overflowText: me.refreshText,
iconCls: Ext.baseCSSPrefix + 'tbar-loading',
handler: me.doRefresh,
scope: me
}
];
},
// #private
onLoad: function () {
var me = this,
pageData,
pageSize,
currPage,
pageCount,
afterText,
count,
isEmpty;
count = me.store.getCount();
isEmpty = count === 0;
if (!isEmpty) {
pageData = me.getPageData();
pageSize = pageData.pageSize ? pageData.pageSize : me.objectsPerPageDefault;
currPage = pageData.currentPage;
pageCount = pageData.pageCount;
afterText = Ext.String.format(me.afterPageText, isNaN(pageCount) ? 1 : pageCount);
} else {
pageData = me.objectsPerPageDefault;
currPage = 0;
pageCount = 0;
afterText = Ext.String.format(me.afterPageText, 0);
}
Ext.suspendLayouts();
me.child('#afterTextItem').setText(afterText);
me.child('#inputItem').setDisabled(isEmpty).setValue(currPage);
me.child('#first').setDisabled(currPage === 1 || isEmpty);
me.child('#prev').setDisabled(currPage === 1 || isEmpty);
me.child('#next').setDisabled(currPage === pageCount || isEmpty);
me.child('#last').setDisabled(currPage === pageCount || isEmpty);
me.child('#comboItemsCount').setDisabled(isEmpty).setValue(pageSize);
me.child('#refresh').enable();
me.updateInfo();
Ext.resumeLayouts(true);
if (me.rendered) {
me.fireEvent('change', me, pageData);
}
},
// #private
getPageData: function () {
var store = this.store,
totalCount = store.getTotalCount();
return {
total: totalCount,
pageSize: store.pageSize,
currentPage: store.currentPage,
pageCount: Math.ceil(totalCount / store.pageSize),
fromRecord: ((store.currentPage - 1) * store.pageSize) + 1,
toRecord: Math.min(store.currentPage * store.pageSize, totalCount)
};
},
//#private
onItemsPerPageChange: function (combo, newValue) {
var me = this;
if(newValue) {
me.store.pageSize = newValue;
me.store.loadPage(1);
}
}
});

ui-grid remove selected row not working

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

Resources