How to add rowCount in tooltip of google charts - angularjs

I am using google chart to display my data on screen. Data is aggregated using using one of the column as shown below...
var dataGroup = google.visualization.data.group(
data, // data table
[0], // group by column
[
{ // aggregation column
column: 1,
type: 'number',
aggregation: google.visualization.data.avg
}
]
);
chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(dataGroup, $scope.getOptionsForChart());
Now what I want to do is add row count in tooltip.
THanks in advance.

there are no standard options for adding information to the tooltip,
you must replace the entire tooltip with your own custom one...
two things must be in place to use custom html tooltips...
1) must use the following chart option...
tooltip: {
isHtml: true
}
2) the tooltip column must have the following property...
p: {html: true}
see following working snippet...
an aggregation column is added for the count
then a DataView is used to convert the count column to a tooltip column
however, when using a DataView, for some reason the html column property is ignored
so when the chart is drawn, convert the DataView back to a DataTable,
chart.draw(view.toDataTable(), ...
this will allow the chart to recognize the column property...
google.charts.load('current', {
callback: function () {
var datastring = '{"PerformanceData" : [{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"},{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"},{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"}]}';
var jsonData = JSON.parse(datastring);
var chartData = [];
// load chart data
jsonData.PerformanceData.forEach(function (row, rowIndex) {
// column headings
var columns = Object.keys(row);
if (rowIndex === 0) {
chartData.push(columns);
}
// row values
var chartRow = [];
columns.forEach(function (column, colIndex) {
var chartCell = row[column];
if (colIndex > 0) {
chartCell = parseFloat(chartCell);
}
chartRow.push(chartCell);
});
chartData.push(chartRow);
});
var data = google.visualization.arrayToDataTable(chartData);
// group data
var dataGroup = google.visualization.data.group(
data, // data table
[0], // group by column
[
{ // average
column: 1,
type: 'number',
aggregation: google.visualization.data.avg,
label: data.getColumnLabel(1)
},
{ // count
column: 1,
type: 'number',
aggregation: google.visualization.data.count
}
]
);
var view = new google.visualization.DataView(dataGroup);
view.setColumns([0, 1, {
type: 'string',
role: 'tooltip',
calc: function (dt, row) {
return '<div class="tooltip">' +
'<div><span>' + dt.getValue(row, 0) + '</span></div>' +
'<div><span>' + dt.getColumnLabel(1) + ' (avg): </span>' + dt.getValue(row, 1) + '</div>' +
'<div><span>Row Count: </span>' + dt.getValue(row, 2) + '</div>' +
'</div>';
},
p: {html: true}
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
// use group data to draw chart
chart.draw(view.toDataTable(), {
tooltip: {
isHtml: true
}
});
},
packages: ['corechart']
});
.tooltip {
font-size: 12pt;
padding: 8px;
}
.tooltip div {
padding: 4px;
}
.tooltip span {
font-weight: bold;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

google.visualization.DataTable(JSON.parse(datastring)) is not working

I am using google charts to display some data on the screen and on some button click. The data is loading from webapi call.
To simplyfy the issue, I made the data hardcoded in function itself.
The issue is when I call
google.visualization.DataTable(JSON.parse(datastring))
Message: Table has no columns.
it is returning empty datatable. I also tried with arrayToDatable but no use.
I got error with arrayToDataTable. here is it.
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys
I have create a plunker for it.
http://plnkr.co/edit/pctIqoCWi3LhqxlgdnqM?p=preview
Can anyone have a look and let me know whats wrong with this.
when creating google.visualization.DataTable directly from json,
the json must be in a specific format
see --> Format of the Constructor's JavaScript Literal data Parameter
google.visualization.arrayToDataTable accepts an array of values, not objects...
[["ReportName","ReportTime"],["ABC",48],["XYZ",50]]
if you don't want to change the format of the results from the webapi call,
you'll need to transform the data for the chart
see following working snippet for an example...
google.charts.load('current', {
callback: function () {
var datastring = '{"PerformanceData" : [{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"}]}';
var jsonData = JSON.parse(datastring);
var chartData = [];
// load chart data
jsonData.PerformanceData.forEach(function (row, rowIndex) {
// column headings
var columns = Object.keys(row);
if (rowIndex === 0) {
chartData.push(columns);
}
// row values
var chartRow = [];
columns.forEach(function (column, colIndex) {
var chartCell = row[column];
if (colIndex > 0) {
chartCell = parseFloat(chartCell);
}
chartRow.push(chartCell);
});
chartData.push(chartRow);
});
var data = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240 });
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
EDIT
once the data table is built, use the group() method to aggregate the data
you can use one of the provided aggregation functions, or provide your own
google.visualization.data.avg
google.visualization.data.count
google.visualization.data.max
google.visualization.data.min
google.visualization.data.sum
see following working snippet...
google.charts.load('current', {
callback: function () {
var datastring = '{"PerformanceData" : [{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"},{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"},{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"},{"ReportName":"ABC","ReportTime":"48"},{"ReportName":"XYZ","ReportTime":"50"}]}';
var jsonData = JSON.parse(datastring);
var chartData = [];
// load chart data
jsonData.PerformanceData.forEach(function (row, rowIndex) {
// column headings
var columns = Object.keys(row);
if (rowIndex === 0) {
chartData.push(columns);
}
// row values
var chartRow = [];
columns.forEach(function (column, colIndex) {
var chartCell = row[column];
if (colIndex > 0) {
chartCell = parseFloat(chartCell);
}
chartRow.push(chartCell);
});
chartData.push(chartRow);
});
var data = google.visualization.arrayToDataTable(chartData);
// group data
var dataGroup = google.visualization.data.group(
data, // data table
[0], // group by column
[{ // aggregation column
column: 1,
type: 'number',
aggregation: google.visualization.data.sum
}]
);
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
// use group data to draw chart
chart.draw(dataGroup, {
pieSliceText: 'value',
width: 400,
height: 240
});
},
packages:['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Can a subgrid be exported in angular ui-grid

I'm using the grid from http://ui-grid.info/ in a project. I've created a hierarchical grid, which works nicely, but when I do an export, it only exports the data from the top-level grid.
This is by design and is standard functionality for the grid, so there's no point in me putting up any example code. Any example from http://ui-grid.info/docs/#/tutorial will do.
Is there a way to export the subgrid (preferably both the main grid AND the subgrid together as they appear in the grid)?
Sadly the answer is no.
As you can see here the function getData iterates through all rows and then through all columns, adding to an array of extractedFields the columns to be extracted and aggregating those in an array of extractedRows.
This means that no data, other than what's defined in gridOptions' columnDef will be read, converted and extracted.
By design, subgrid information are stored inside a property of any row entity's subGridOptions but this property is never accessed inside of the exporter feature.
The motivation behind this behaviour is that expandable grid feature is still at an alpha stage, so, supporting this in other features is not a compelling priority.
Furthermore, adding subgrid to a CSV could be quite hard to design, if we wanted to provide a general solution (for example I don't even think it would be compliant to CSV standard if you had different number of columns in the main grid and in subgrids).
That said, ui-grid is an open source project, so, if you have a working design in mind, feel free to open a discussion about it on the project gitHub page or, even better, if you can design a working (and tested) solution and create a pull request, even better!
I managed to get it working, although if I had the time I would do it a bit better than what I've done by actually creating a branch of the code and doing it properly, but given time constraints, what I've got is working nicely.
FYI, here's the way I ended up getting it to do what I wanted:
In my grid options, I turned off the CSV export options in the grid menu (because I've only implemented the changes for PDF).
I made a copy of exporter.js, named it custom.exporter.js and changed my reference to point to the new file.
In custom.exporter.js, I made a copy of the getData function and named it getGridRows. getGridRows is the same as getData, except it just returns the rows object without all the stuff that gets the columns and so on. For now, I'm coding it to work with a known set of columns, so I don't need all that.
I modified the pdfExport function to be as follows:
pdfExport: function (grid, rowTypes, colTypes) {
var self = this;
var exportData = self.getGridRows(grid, rowTypes, colTypes);
var docContent = [];
$(exportData).each(function () {
docContent.push(
{
table: {
headerRows: 1,
widths: [70, 80, 150, 180],
body: [
[{ text: 'Job Raised', bold: true, fillColor: 'lightgray' }, { text: 'Job Number', bold: true, fillColor: 'lightgray' }, { text: 'Client', bold: true, fillColor: 'lightgray' }, { text: 'Job Title', bold: true, fillColor: 'lightgray' }],
[formattedDateTime(this.entity.JobDate,false), this.entity.JobNumber, this.entity.Client, this.entity.JobTitle],
]
}
});
var subGridContentBody = [];
subGridContentBody.push([{ text: 'Defect', bold: true, fillColor: 'lightgray' }, { text: 'Vendor', bold: true, fillColor: 'lightgray' }, { text: 'Status', bold: true, fillColor: 'lightgray' }, { text: 'Sign off', bold: true, fillColor: 'lightgray' }]);
$(this.entity.Defects).each(function () {
subGridContentBody.push([this.DefectName, this.DefectVendor, this.DefectStatus, '']);
});
docContent.push({
table: {
headerRows: 1,
widths: [159, 150, 50, 121],
body: subGridContentBody
}
});
docContent.push({ text: '', margin: 15 });
});
var docDefinition = {
content: docContent
}
if (self.isIE()) {
self.downloadPDF(grid.options.exporterPdfFilename, docDefinition);
} else {
pdfMake.createPdf(docDefinition).open();
}
}
No, there is no direct way to export subgrid. rather you can create youur own json data to generate csv file.
Please check the below code
function jsonToCsvConvertor(JSONData, reportTitle) {
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData !== 'object' ? JSON.parse(JSONData) : JSONData,
csv = '',
row,
key1,
i,
subGridData;
//Set Report title in first row or line
csv += reportTitle + '\r\n\n';
row = '';
for (key1 in arrData[0]) {
if(key1 !== 'subGridOptions' && key1 !== '$$hashKey'){
row += key1 + ',';
}
}
csv += row + '\r\n';
for (i = 0; i < arrData.length; i++) {
row = '';
subGridData = '';
for (key1 in arrData[i]) {
if(key1 !== 'subGridOptions' && key1 !== '$$hashKey'){
row += '"' + arrData[i][key1] + '",';
}
else if(key1 === 'subGridOptions'){
//csv += row + '\r\n';
subGridData = writeSubGridData(arrData[i][key1].data);
}
}
csv += row + '\r\n';
csv = subGridData ? csv + subGridData + '\r\n' : csv;
}
if (csv === '') {
console.log('Invalid data');
}
return csv;
}
//Generates subgrid Data to exportable form
function writeSubGridData(subgridData){
var j,
key2,
csv = '',
row = '';
for (key2 in subgridData[0]){
if(key2 !== '$$hashKey'){
row += key2 + ',';
}
}
csv = row + '\r\n';
for (j=0; j < subgridData.length ; j++){
row = '';
for(key2 in subgridData[j]){
if(key2 !== '$$hashKey'){
row += '"' + subgridData[j][key2]+ '",';
}
}
csv += row + '\r\n';
}
return csv;
}
jsonToCsvConvertor(exportData, 'New-Report');

How do I put a checkbox in the title/label of a Dojo TabContainer?

I want to put a checkbox in the label of a Dojo TabContainer. I found an example here:
http://telliott.net/dojoExamples/dojo-checkboxTabExample.html
However, the example only shows html. I would like to do this programmatically. This is what I have so far:
function(response){
var json_response = JSON.parse(response);
var fields_dict = json_response['fields_dict'];
var names_dict = json_response['names_dict'];
var tc = new TabContainer({
style: "height: 495px; width: 100%;",
tabPosition: "left",
tabStrip: true
}, "report_tab_container");
for(var key in fields_dict) {
var content_string = '';
var fields = fields_dict[key];
for(var field in fields) content_string += '<div>' + fields[field][0] + fields[field][1] + '</div>';
var checkBox = new CheckBox({
name: "checkBox",
value: "agreed",
checked: false,
onChange: function(b){ alert('onChange called with parameter = ' + b + ', and widget value = ' + this.get('value') ); }
}).startup();
var tcp = new ContentPane({
//title: names_dict[key],
title: checkBox,
content: content_string
});
tc.addChild(tcp);
}
tc.startup();
tc.resize();
},
However, this doesn't work. When I load my page, the TabContainer doesn't show up. If I set the title of my ContentPane to something other than my check box, it works fine.
What am I doing wrong and how do I get the checkbox to appear in the TabContainer title?
This is what worked:
cb.placeAt('report_tab_container_tablist_dijit_layout_ContentPane_'+ i.toString(), "first");
I'm doing this blindly here, but comparing the example on your link to your code, I would say, add this before tc.addChild(tcp) :
checkBox.placeAt(tcp.domNode, "first");

How to get the value of a checkbox in a Kendo UI Grid?

So I've searched many of the answers and can't seem to find anything specific on this... so here goes..
I have a standard Kendo UI Grid - and I've setup a column as follows:
{ title: "Sharing Enabled?",
field: "permissions_users_apps_user_sharing",
attributes: {
style: "text-align: center; font-size: 14px;"
},
filterable: true,
headerAttributes: {
style: "font-weight: bold; font-size: 14px; width: 40px;"
},
template: function(dataItem) {
if ( dataItem.permissions_users_apps_user_sharing == 0 ) {
return "<input type='checkbox' name='permissions_users_apps_status' id='permissions_users_apps_status' value='1' />"
} else if ( dataItem.permissions_users_apps_user_sharing == 1 ) {
return "<input type='checkbox' name='permissions_users_apps_status' id='permissions_users_apps_status' value='1' checked />"
}
}
},
What I'm trying to do is get the value of this checkbox (to see if it's changed) when I click a COMMAND button I've defined. The ROW is selectable.. so I can get the row's ID. But I can't seem to gather the value of the checkbox.
Anyone have suggestions?
Thanks in advance..
You can get the instance of checkbox in dataBound event when the checkbox state changes.
See if the below code helps you.
....
columns: [
{
{ field: "select", template: '<input id="${BindedColumn}" onclick="GrabValue(this)" type="checkbox"/>', width: "35px", title: "Select" },
}
....
selectable: "multiple, row",
dataBound: function () {
var grid = this;
//handle checkbox change
grid.table.find("tr").find("td:nth-child(1) input")
.change(function (e) {
var checkbox = $(this);
//Write code to get checkbox properties for all checkboxes in grid
var selected = grid.table.find("tr").find("td:nth-child(1) input:checked").closest("tr");
//Write code to get selected checkbox properties
......
//Code below to clear grid selection
grid.clearSelection();
//Code below to select a grid row based on checkbox selection
if (selected.length) {
grid.select(selected);
}
})
}
.....
function GrabValue(e)
{
//Alert the checkbox value
alert(e.value);
//get the grid instance
var grid = $(e).closest(".k-grid").data("kendoGrid");
//get the selected row data
var dataItem = grid.dataSource.view()[grid.select().closest("tr").index()];
}
using this method you get selected checkbox value.
$("#MultiPayment").click(function () {
var idsToSend = [];
var grid = $("#Invoice-grid").data("kendoGrid")
var ds = grid.dataSource.view();
for (var i = 0; i < ds.length; i++) {
var row = grid.table.find("tr[data-uid='" + ds[i].uid + "']");
var checkbox = $(row).find(".checkboxGroups");
if (checkbox.is(":checked")) {
idsToSend.push(ds[i].Id);
}
}
alert(idsToSend);
$.post("/whatever", { ids: idsToSend });
});
for more detail Goto

Export google chart?

I wrote this code to create chart, table and toolbar.
google.load("visualization", "1", { packages: ["corechart"] });
google.load('visualization', '1', { packages: ['table'] });
//google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "GET",
url: '#Url.Action("GunlukOkumalar", "Enerji")',
data: "startDate=" + $('#start_date').val() + "&endDate=" + $('#end_date').val() + "&sayac_id=" + $("#sayaclar").val(), //belirli aralıklardaki veriyi cekmek için
success: function (result) {
if (result.success) {
var evalledData = eval("(" + result.chartData + ")");
var opts = { curveType: "function", width: '100%', height: 500, pointSize: 5 };
new google.visualization.LineChart($("#chart_div").get(0)).draw(new google.visualization.DataTable(evalledData, 0.5), opts);
$('#chart_div').show();
var visualization;
var data;
var options = { 'showRowNumber': true };
data = new google.visualization.DataTable(evalledData, 0.5);
// Set paging configuration options
// Note: these options are changed by the UI controls in the example.
options['page'] = 'enable';
options['pageSize'] = 10;
options['pagingSymbols'] = { prev: 'prev', next: 'next' };
options['pagingButtonsConfiguration'] = 'auto';
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, options);
var components = [
{ type: 'html', datasource: data },
{ type: 'csv', datasource: data }
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
return false;
}
else {
$('#chart_div').html('<span style="color:red;"><b>' + result.Error + '</b></span>');
$('#chart_div').show();
$('#table').html('<span style="color:red;"><b>' + result.Error + '</b></span>');
$('#table').show();
return false;
}
}
});
}
Google example
function drawToolbar() {
var components = [
{type: 'igoogle', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA',
gadget: 'https://www.google.com/ig/modules/pie-chart.xml',
userprefs: {'3d': 1}},
{type: 'html', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
{type: 'csv', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA'},
{type: 'htmlcode', datasource: 'https://spreadsheets.google.com/tq?key=pCQbetd-CptHnwJEfo8tALA',
gadget: 'https://www.google.com/ig/modules/pie-chart.xml',
userprefs: {'3d': 1},
style: 'width: 800px; height: 700px; border: 3px solid purple;'}
];
var container = document.getElementById('toolbar_div');
google.visualization.drawToolbar(container, components);
};
Google get dataSource from url, but I get dataSource dynamicly from controller. When I try to export It forwards page to another page like this:
http://localhost:49972/Enerji/%5Bobject%20Object%5D?tqx=out%3Acsv%3B
How can I use exporting toolbar for dynamic Json data? Is there any example about this topic?
I also had this problem and after a lot of trawling I found this!
https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
I haven't implemented it yet but I reckon it's the way to go.

Resources