Show Aggregation value in chart.

By reading a JSON I am currently populating given table using ui.grid grouping module. And just right of that there is a chart where I am trying to show state->member mapping (means how many male/female members are there in a particular state). So how can I calculate state->member cardinality ratio so that I can populate stateList[] to show pie chart. In the screenshot I had marked some field in RED, I had to store all the marked value in stateList[].
For displaying the chart Fn "changeView" is calling. <Currently stateList[] array is just a hard coded array>.
For chart representation I am using "highcharts-ng" .
columnDefn.JSON is given below------------->
[ { "name": "name", "width": "30%", "displayName": "Full Name", "enableCellEdit": false, "filter": { "condition": "ENDS_WITH", "placeholder": "ends with" }, "aggregationType": "count", "aggregationHideLabel": false }, { "name": "gender", "grouping": { "groupPriority": 1 }, "sort": { "priority": 1, "direction": "asc" }, "width": "20%" }, { "name": "age", "grouping": { "aggregation": "avg" }, "width": "20%" }, { "name": "company", "width": "25%" }, { "name": "state", "grouping": { "groupPriority": 0 }, "sort": { "priority": 0, "direction": "desc" }, "width": "35%" }, { "name": "balance", "width": "25%", "cellFilter": "currency", "groupingSuppressAggregationText": true, "grouping": { "aggregation": "avg" } } ]
App.js -------------->
var app = angular.module('app', ['ui.bootstrap', 'highcharts-ng', 'app.jsonServices', 'ngAnimate', 'ngTouch', 'ui.grid', 'ui.grid.grouping', 'ui.grid.pinning', 'ui.grid.edit', 'ui.grid.cellNav', 'ui.grid.resizeColumns', 'ui.grid.exporter', 'ui.grid.saveState', 'ui.grid.moveColumns', 'ui.grid.pagination', 'ui.grid.autoResize', 'ui.grid.selection']);
app.controller('MainCtrl', ['$scope', '$http', '$interval', 'uiGridGroupingConstants', 'uiGridConstants', '$log', 'jsonServices', function ($scope, $http, $interval, uiGridGroupingConstants, uiGridConstants, $log, jsonServices) { //$scope.colList = []; $scope.toolTip = ''; $scope.initializeTreeHeaderDefn = function () { $scope.successfn = function (retdata) { if (retdata.flag) { if (retdata.data !== null) { $scope.columnDefn = retdata.data; } } else { $scope.columnDefn = retdata.data; } if (angular.isDefined($scope.promise)) { $interval.cancel($scope.promise); $scope.promise = undefined; } if ($scope.columnDefn.length > 0) { angular.forEach($scope.columnDefn, function (value, key) {
//$scope.toolTip = $scope.toolTip + " , " + value.name;
//alert(JSON.stringify(value.grouping.aggregation));
if (value.grouping !== undefined) {
if (value.grouping.aggregation !== "") {
if (value.grouping.aggregation === "max") {
value.grouping.aggregation = uiGridGroupingConstants.aggregation.MAX;
}
else if (value.grouping.aggregation === "min") {
value.grouping.aggregation = uiGridGroupingConstants.aggregation.MIN;
}
else if (value.grouping.aggregation === "count") {
value.grouping.aggregation = uiGridGroupingConstants.aggregation.COUNT;
}
else if (value.grouping.aggregation === "avg") {
value.grouping.aggregation = uiGridGroupingConstants.aggregation.AVG;
}
else if (value.grouping.aggregation === "sum") {
value.grouping.aggregation = uiGridGroupingConstants.aggregation.SUM;
}
}
//alert(uiGridGroupingConstants.aggregation.MAX);
}
if (value.aggregationType !== "") {
if (value.aggregationType === "max") {
value.aggregationType = uiGridGroupingConstants.aggregation.MAX;
}
else if (value.aggregationType === "min") {
value.aggregationType = uiGridGroupingConstants.aggregation.MIN;
}
else if (value.aggregationType === "count") {
value.aggregationType = uiGridGroupingConstants.aggregation.COUNT;
}
else if (value.aggregationType === "avg") {
value.aggregationType = uiGridGroupingConstants.aggregation.AVG;
}
else if (value.aggregationType === "sum") {
value.aggregationType = uiGridGroupingConstants.aggregation.SUM;
}
}
if (angular.isDefined(value.filter)) {
if (value.filter.condition === "GREATER_THAN") {
value.filter.condition = uiGridConstants.filter.GREATER_THAN;
}
else if (value.filter.condition === "LESS_THAN") {
value.filter.condition = uiGridConstants.filter.LESS_THAN;
}
else if (value.filter.condition === "CONTAINS") {
value.filter.condition = uiGridConstants.filter.CONTAINS;
}
else if (value.filter.condition === "ENDS_WITH") {
value.filter.condition = uiGridConstants.filter.ENDS_WITH;
}
else if (value.filter.condition === "EXACT") {
value.filter.condition = uiGridConstants.filter.EXACT;
}
else if (value.filter.condition === "GREATER_THAN_OR_EQUAL") {
value.filter.condition = uiGridConstants.filter.GREATER_THAN_OR_EQUAL;
}
else if (value.filter.condition === "LESS_THAN_OR_EQUAL") {
value.filter.condition = uiGridConstants.filter.LESS_THAN_OR_EQUAL;
}
else if (value.filter.condition === "NOT_EQUAL") {
value.filter.condition = uiGridConstants.filter.NOT_EQUAL;
}
else if (value.filter.condition === "STARTS_WITH") {
value.filter.condition = uiGridConstants.filter.STARTS_WITH;
}
}
// if (angular.isDefined(value.cellTooltip) && value.cellTooltip === "Y") { // value.cellTooltip = $scope.toolTip; // }
$scope.colDefnPopulated = true;
console.log($scope.toolTip);
});
}
};
$scope.failureFn = function (retFaileddata) {
//console.log("INSIDE FAILURE SERVICE");
};
jsonServices.getTreeTableHeader($scope.successfn, $scope.failureFn);
};
$scope.promise = $scope.initializeTreeHeaderDefn();
$scope.initializeTreeDataDefn = function () {
$scope.successfn = function (retdata) {
if (retdata.flag) {
if (retdata.data !== null) {
//$scope.gridOptions.data = retdata.data;
for (var i = 0; i < retdata.data.length; i++) {
retdata.data[i].state = retdata.data[i].address.state;
retdata.data[i].balance = Number(retdata.data[i].balance.slice(1).replace(/,/, ''));
}
delete retdata.data[9].age;
$scope.gridOptions.data = retdata.data;
}
} else {
//$scope.gridOptions.data = retdata.data;
if (retdata.data !== null) {
//$scope.gridOptions.data = retdata.data;
for (var i = 0; i < retdata.data.length; i++) {
retdata.data[i].state = retdata.data[i].address.state;
retdata.data[i].balance = Number(retdata.data[i].balance.slice(1).replace(/,/, ''));
}
delete retdata.data[2].age;
$scope.gridOptions.data = retdata.data;
}
}
if (angular.isDefined($scope.promise)) {
$interval.cancel($scope.promise);
$scope.promise = undefined;
}
};
$scope.failureFn = function (retFaileddata) {
//console.log("INSIDE FAILURE SERVICE");
};
jsonServices.getTreeTableData($scope.successfn, $scope.failureFn);
};
$scope.promise = $scope.initializeTreeDataDefn();
$scope.$watch('columnDefn', function () {
if (angular.isDefined($scope.columnDefn) && $scope.columnDefn.length > 0 && $scope.colDefnPopulated) {
$scope.gridOptions.columnDefs = $scope.columnDefn;
}
});
$scope.gridOptions = {
enableSelectAll: true,
saveFocus: false,
saveScroll: true,
paginationPageSize: 14,
showColumnFooter: true,
//showGridFooter: true,
enableGridMenu: true,
enableFiltering: false,
modifierKeysToMultiSelectCells: true,
exporterCsvFilename: 'myFile.csv',
exporterPdfDefaultStyle: {fontSize: 9},
exporterPdfTableStyle: {margin: [30, 30, 30, 30]},
exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red'},
exporterPdfHeader: {text: "My Header", style: 'headerStyle'},
exporterPdfFooter: function (currentPage, pageCount) {
return {text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle'};
},
exporterPdfCustomFormatter: function (docDefinition) {
docDefinition.styles.headerStyle = {fontSize: 22, bold: true};
docDefinition.styles.footerStyle = {fontSize: 10, bold: true};
return docDefinition;
},
exporterPdfOrientation: 'portrait',
exporterPdfPageSize: 'LETTER',
exporterPdfMaxGridWidth: 500,
exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")),
//columnDefs: $scope.colDefn,
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
}
};
$scope.expandAll = function () {
$scope.gridApi.grouping.
$scope.gridApi.grouping.expandAllRows();
};
$scope.toggleRow = function (rowNum) {
$scope.gridApi.grouping.toggleRowGroupingState($scope.gridApi.grid.renderContainers.body.visibleRowCache[rowNum]);
};
//This needs to be change programatically
$scope.changeGrouping = function () {
$scope.gridApi.grouping.clearGrouping();
$scope.gridApi.grouping.groupColumn('age');
$scope.gridApi.grouping.aggregateColumn('state', uiGridGroupingConstants.aggregation.COUNT);
};
//add new row to table
$scope.addData = function () {
$scope.gridOptions.intermediateData = [];
$scope.gridOptions.data.forEach(function addDatas(row, index) {
if ($scope.gridOptions.paginationPageSize === (index + 1)) {
$scope.gridOptions.intermediateData.push({});
} else {
$scope.gridOptions.intermediateData.push($scope.gridOptions.data[index]);
}
});
$scope.gridOptions.data = [];
$scope.gridOptions.data = $scope.gridOptions.intermediateData;
grid.redrawInPlace();
//need to add css for indentification.
// after editing correctly make it as a normal column.
};
$scope.msg = {};
$scope.gridOptions.onRegisterApi = function (gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
$scope.msg.lastCellEdited = 'Edited row id: ' + rowEntity.id + ' Column: ' + colDef.name + ' newValue: ' + newValue + ' oldValue: ' + oldValue;
$scope.$apply();
});
};
//toggle Filter from table
$scope.toggleFiltering = function () {
$scope.gridOptions.enableFiltering = !$scope.gridOptions.enableFiltering;
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
};
//Remove one or multiple selected Rows.
$scope.removeRow = function () {
angular.forEach($scope.gridApi.selection.getSelectedRows(), function (data, index) {
$scope.gridOptions.data.splice($scope.gridOptions.data.lastIndexOf(data), 1);
});
}
//Save Current state
$scope.state = {};
$scope.saveState = function () {
$scope.state = $scope.gridApi.saveState.save();
};
//Restore state
$scope.restoreState = function () {
$scope.gridApi.saveState.restore($scope, $scope.state);
};
// $scope.tableClass = 'col-sm-12';
$scope.revertView = function () {
$scope.chartStructure = false;
};
$scope.chartStructure = false;
// Start of chart Representation------------------------------------------------------
$scope.bar = function () {
this.chartConfig.options.chart.type = 'bar'
};
$scope.line = function () {
this.chartConfig.options.chart.type = 'line'
this.chartConfig.options.chart.zoomType = 'x'
};
$scope.pie = function () {
this.chartConfig.options.chart.type = 'pie'
};
$scope.chartConfig = {
options: {
chart: {
type: 'pie'
}
},
series: [{
data: []
}],
title: {
text: 'Data Reprentaion'
},
loading: false
};
$scope.$watch('colList', function () {
if (angular.isDefined($scope.colList) && $scope.colList.length > 0) {
$scope.chartConfig.series[0].data = $scope.colList;
}
});
$scope.changeView = function () {
$scope.chartStructure = true;
$scope.colList = [40, 30, 31, 33, 28, 20, 29, 21];
//$scope.stateList = [];
var i = 0;
$scope.gridOptions.data.forEach(function getColData(row,col,index,GridColumn) {
$scope.stateList[i] = row.state;
i++;
});
};
}]);
The grouping data is calculated as part of a rowsProcessor - we run through all the rows one by one and write out the totals onto the groupHeaderRow as we go. They're never all in one big array in memory.
In theory you can extract them from the groupHeaderRow - so if you ran through all the rows, and looked at each row that had row.groupHeader === true, then the values in the row.entity are the aggregation totals. That's probably quicker than recalculating them.
In that way I am navigating grid data and populating topGroupList[]. In this logic I am mentioning aggregated field "state" hard coded. But I am trying to pass aggregated field name with scope variable keyGroupName and then trying to use row.
How it can be dynamic?
$scope.gridOptions.data.forEach(function getColData(row,col,index,GridColumn) {
var rowProp = $scope.keyGroupName;
$scope.topGroupList[i] = row.state; // need row.
Sorry, I have no idea what you're doing there, but it doesn't look right.
What is it that you would expect to be in the state property? State of what?
If I was trying to get out the headers, my code would be something like:
var headers = [];
$scope.gridApi.grid.renderContainers.body.visibleRowsCache.forEach( function( row, index ) {
if( row.groupHeader ) {
headers.push ( { label: row.entity.field1, value: row.entity.field2 } );
}
});
I'm assuming here that field1 is the field you're grouping by, and field2 the field you're aggregating by.
You'll probably have to do some work to remove the count from field1, because it'll be formatted like xxx (10), and you'll need to take the (10) out.
Kindly find above "screenshotLatest" for my data details. I have below field in my data table.
- State
- Gender
- Full Name.
- Age etc
My Column Defn is like:
[ { "name": "name", "filter": { "condition": "ENDS_WITH", "placeholder": "ends with" }, "aggregationType": "count", "aggregationHideLabel": false }, { "name": "gender", "grouping": { "groupPriority": 1 }, "sort": { "priority": 1, "direction": "asc" } }, { "name": "age", "grouping": { "aggregation": "avg" }, "width": "20%" }, { "name": "company", "width": "25%" }, { "name": "state", "grouping": { "groupPriority": 0 }, "sort": { "priority": 0, "direction": "desc" }, "width": "35%" } ].
I have two requirements:
- Populate a 2D array where I can store how many members are in state <In screenshot for INDIA it is 4>.
- Also in a different array I have to store how many male and female members are there for a state.<In screenshot for INDIA there are 1 female and 3 male members are there.>

Have you tried the approach I suggested above?
My code is something like that:
$scope.prepareBaseChartStructure = function () { var headers = []; $scope.gridApi.grid.renderContainers.body.visibleRowsCache.forEach(function (row) { if (row.groupHeader) { headers.push({label: row.entity.state, value: row.entity.name}); } }); };
I am getting below error:
undefined
angular.js:10072 TypeError: Cannot read property 'forEach' of undefined
at Scope.$scope.prepareBaseChartStructure (app.js:449)
at Scope.$scope.changeView (app.js:444)
at angular.js:10847
at angular-touch.js:441
at Scope.$eval (angular.js:12702)
at Scope.$apply (angular.js:12800)
at HTMLAnchorElement.
Right. So the array is undefined. Did we use the wrong name (check in the debugger). Did you do onRegisterApi (you can find this in the tutorials).
I had defined my column definition where I had use onRegisterApi for gridApi.
$scope.gridOptions = { enableSelectAll: true, saveFocus: false, saveScroll: true, paginationPageSize: 14, showColumnFooter: true, //showGridFooter: true, enableGridMenu: true, enableFiltering: false, onRegisterApi: function (gridApi) { $scope.gridApi = gridApi; } };
$scope.prepareBaseChartStructure = function () {
var headers = [];
console.log(angular.isDefined($scope.gridApi.grid.renderContainers.body));
console.log(angular.isDefined($scope.gridApi.grid.renderContainers.body.visibleRowsCache));
$scope.gridApi.grid.renderContainers.body.visibleRowsCache.forEach(function (row) {
if (row.groupHeader) {
headers.push({label: row.entity.state, value: row.entity.name});
}
});
};
In console :
console.log(angular.isDefined($scope.gridApi.grid.renderContainers.body)); --> TRUE console.log(angular.isDefined($scope.gridApi.grid.renderContainers.body.visibleRowsCache))--> FALSE
You had mentioned array undefined, but which array is this?
visibleRowsCache is an array, that's why we can call forEach on it. Perhaps it's really visibleRowCache or something like that.
So how can I define "visibleRowCache" so that we can call forEach?
My current version of ui-grid-unstable.js v3.0.0.
angular.isArray($scope.gridApi.grid.renderContainers.body.visibleRowCache) value is coming TRUE.
Although error is coming in below line:
$scope.gridApi.grid.renderContainers.body.visibleRowsCache.forEach(function getTableVisibleContent(row) { //my logic... }
Your quick response is really appreciated.
I think one is row and the other is rows
Thanks a ton Paul.