Kendo + Angular chart data - javascript

I'm trying out Kendo charts with angular, and I have problem displaying data, here is my code:
HTML:
<div kendo-chart="rchart" data-k-options="chartOptions" data-role="chart" class="k-chart" style="position: relative;"></div>
Javascript:
resultService.getResult().then(function (resultResponse) {
$scope.data = resultResponse.data;
$scope.oldReps = _.pluck($scope.data.TreningScores.Item1, 'Item2');
$scope.newReps = _.pluck($scope.data.TreningScores.Item2, 'Item2');
$scope.categories = _.pluck($scope.data.TreningScores.Item1, 'Item1');
});
$scope.chartOptions = {
legend: {
position: "bottom"
},
seriesDefaults: {
type: "column"
},
series: [{
name: "Total Visits",
data: $scope.oldReps
}, {
name: "Unique visitors",
data: $scope.newReps
}],
valueAxis: {
line: {
visible: false
}
},
tooltip: {
visible: true,
format: "{0}"
}
};
The problem is chart isn't updated after data is fetched from server, I've tried refreshing chart like this (but with no luck):
$scope.chart = {
refreshChart : function() {
$scope.rchart.refresh();
},
};
And calling this method in:
resultService.getResult().then(function (resultResponse) {});
And I've also tried to define $scope.chartOptions inside same function, but nothing. Is there any way to fix this ?

It's not well documented, but to get a UI control with remote data-binding to update after data has been returned from a server requires both watching the collection for updates from the Angular side and rebinding the data object to its respective UI control from the Kendo side.
In your controller, watch for changes to your data objects using $watchCollection, and update the objects/properties which are bound to those collections:
// API call
$http.get('...').success(function(data){
$scope.data = data;
});
// KendoUI config object
$scope.chart = {
dataSource: {
data: $scope.data
}
};
// Watch for changes to $scope.data
$scope.$watchCollection('data', function(newData) {
// Update data bindings with changes
$scope.chart.dataSource.data = newData;
});
In your view, define the object your UI control should be bound to when changes are made via the k-rebind Angular-Kendo directive:
<div kendo-chart k-options="chart" k-rebind="chart"></div>
Here is an example of a chart bound to remote data:
http://codepen.io/micjamking/pen/4980a5e22cbd4de01264fadae5f25f06

The use of $watchCollection to track and assign the dataSource.data in the accepted answer and others is a needlessly convoluted approach.
Here's a straightforward implementation:
view:
<div kendo-chart k-theme='metro' k-options="chart" k-rebind="chart"></div>
controller:
$scope.chart = {
dataSource: new kendo.data.DataSource({
data: [{ title: "Loading", value: 100, color: '#EFEFEF' }]
}),
series: [{ field: 'value', categoryField: 'title', padding: 0, holeSize: 25 }],
seriesDefaults: { type: 'donut', startAngle: 90 }
};
Using the dataSource.data() method instead of assigning dataSource.data as an array is the key here:
payrollService.load(userId).then(function (result) {
$scope.chart.dataSource.data(result.items); //where result.items is an array like so:
//[
// { title: "Net Pay", value: 60, color: '#6BAE4B' },
// { title: "Taxes", value: 15, color: '#ED6347' },
// { title: "Deductions", value: 25, color: '#8161C2' }
//]
});
Codepen Demo:
http://codepen.io/TaeKwonJoe/pen/WGOpEv

I think your problem is that $scope.chartOptions is set before the data of the resultService is retrieved. Angular is returning an empty array in this case and filling in the data later.
But $scope.chartOptions not not updated with new data.
You could try with
$scope.$watchCollection('oldReps', function(newData, oldData) {
$scope.chartOptions.series[0].data = newData;
});
$scope.$watchCollection('newReps', function(newData, oldData) {
$scope.chartOptions.series[1].data = newData;
});
So chartOptions are updated if oldReps or newReps have changed.
I had a similiar problem and $watchCollection saved my day (Caching data and updating another object for an chart does not work)

Related

Where to add and register the custom attributes in flot-pie chart js?

Although this question has answer at: Adding custom attributes to flot data
but I have tried every possible way but my custom attributes are not showing on click event.
So far I tried this:
html:
<div id="audit_status" class="chart"></div>
JS:
var audit_status = [
{label: "Pending", data: 2, location_value="Majiwada,Pune"},
{ label: "Ongoing", data: 1 location_value="Mumbai"},
];
var options = {
series: {
pie: {
show: true,
label: {
show: true,
radius: 120,
formatter: function (label, series) {
return '<div style="border:1px solid grey;font-size:8pt;text-align:center;padding:5px;color:white;background-color: #90bdce;">' +
label + ' : ' +
series.data[0][1] +
' ('+Math.round(series.percent)+' %)</div>';
},
background: {
opacity: 0.8,
color: '#000'
}
}
}
},
legend: {
show: true
},
grid: {
hoverable: true,
clickable: true
}
};
$("#audit_status").bind("plotclick", function(event, pos, obj) {
console.log(obj);
//alert(obj.series.value);
if (obj) {
alert(obj.series.location_value);
}
});
$(document).ready(function () {
$.plot($("#audit_status"), audit_status, options);
});
The problem is: whenever I click the pie segment I want to alert "location_value"
but i am getting [Object Object]
I see two issues with the code as it is now. First, the audit_status JSON object isn't quite defined right. The location_value properties need to use colons, not equal signs:
var audit_status = [
{ label: "Pending", data: 2, location_value: "Majiwada,Pune" },
{ label: "Ongoing", data: 1, location_value: "Mumbai" }
];
Second, in your plotclick function, the extra properties defined in your data object don't make it over to the series object passed into the callback. You need to reference the original data object, using the obj.seriesIndex provided to the callback. This JSFiddle provides an example of the code below.
var data = [{
label: "Yes",
data: 50,
location_value: 'Majiwada,Pune'
}, {
label: "No",
data: 150,
location_value: 'Mumbai'
}];
// plot initialization code here
$("#pie").bind("plotclick", function(event, pos, obj) {
if (obj) {
// use the obj.seriesIndex to grab the original data object,
// then you can use any property you defined on that object
alert(data[obj.seriesIndex].location_value);
}
});

Two-way binding is not recognising variable change in AngularJS

I have a slider that is used to changed a value in my controller like so
index:
<div>
<rzslider
rz-slider-model="slider.value"
rz-slider-options="slider.options">
</rzslider>
<p>{{slider.value}}</p>
</div>
controller:
app.controller('gbarchartController', function($scope) {
$scope.slider = {
value: 20,
options: {
floor: 0,
ceil: 30
}
};
When i change the value of the slider, the code below displays it on screen as 2 way binding should.
<p>{{slider.value}}</p>
The problem is , if i try to access this variable through a function in my controller, it uses the initial value of 20 that has been set. eg. If i change the slider to 10, the below code still uses the value 20. the variable in question is $scope.slider.value . The value is used to cut the length of an array, that in turn is used to display a graph using highchart.js.
$scope.graph = function(metric) {
Highcharts.chart(metric, {
chart: {
type: 'column'
},
title: {
text: 'Number Of Executions'
},
colors: [
'#7CFC00', '#FF0000'
],
xAxis: {
categories: numExe.hash.slice(0, $scope.slider.value),
title: {
text: 'Query Hash Value'
}
},
yAxis: {
title: {
text: '% of Total Executions'
}
},
tooltip: {
shared:true
},
series: [{
name: 'Baseline',
data: numExe.base.slice(0, $scope.slider.value)
},
{
name: 'Comparative',
data: numExe.compare.slice(0, $scope.slider.value)
}]
});
}
Long story short, The variable changes in the html but does not change in the controller. Any help would be great thanks.
I don't think Highcharts monitors its data for changes, so it won't detect changes to your series data (see docs here). Additionally the series data passed in to the graph is static, so it won't update after the slider changes. You'll need to create a local Series variable to hold the series data, and update the series data when the slider changes. I'm not sure what numExe is so I can't say how the data is generated, but the Series object has setData() method (with a redraw parameter) that should do the trick.

Getting JSON from Google for Highmaps

I'm pretty rusty with JavaScript, so I'm hoping someone can help me out. I'm working with Highmaps and would like to link the map to data in a Google Spreadsheet. (It's a U.S. map of counties which will be updated regularly, so having it all in the script itself is a little unwieldy.)
This is what my code looks like now:
<script type="text/javascript">
var example = 'us-counties',
theme = 'default';
(function($) { // encapsulate jQuery
$(function() {
var data = [{
"code": "us-al-001",
"name": "Autauga County, AL",
"value": 0
},
…
{
"code": "us-pr-153",
"name": "Yauco Municipio, PR",
"value": 0
}],
countiesMap = Highcharts.geojson(Highcharts.maps['countries/us/us-all-all']),
lines = Highcharts.geojson(Highcharts.maps['countries/us/us-all-all'], 'mapline'),
options;
// Add state acronym for tooltip
Highcharts.each(countiesMap, function(mapPoint) {
mapPoint.name = mapPoint.name + ' County, ' + mapPoint.properties['hc-key'].substr(3, 2);
});
series: [{
name: 'County',
mapData: countiesMap,
data: data,
joinBy: ['hc-key', 'code'],
tooltip: {
enabled: true,
positioner: function () {
return { x: 0, y: 250 };
},
pointFormat: '{point.name}',
borders: 0.5
},
borderWidth: 0.5
}, {
type: 'mapline',
name: 'State borders',
data: [lines[0]],
color: 'white'
}, {
type: 'mapline',
name: 'Separator',
data: [lines[1]],
color: 'gray'
}]
};
// Instanciate the map
$('#container').highcharts('Map', options);
});
$(document).ready(function() {
$("#view-menu").click(function(e) {
$("#wrap").toggleClass("toggled");
});
$("#sidebar-close").click(function(e) {
$("#wrap").removeClass("toggled");
});
});
})(jQuery);
</script>
Of course, since there's over 3,200 counties, I'd rather store that data elsewhere and pull it into the var data = [] string, but I'm not sure how to do that.
Any help would be appreciated.
Although this isn't something I've done, it looks like this should be relatively straightforward to do (although nothing is as simple as it looks of course).
There is an API for Google Sheets (https://developers.google.com/google-apps/spreadsheets/) and you can Google examples of how to retrieve data - this one looks clear (https://developers.google.com/gdata/docs/json) although it does point out that there are newer versions of some of the relevant APIs.
If you pull in the JSON data from the Google Sheet you then just need to put the values into the 'value' element of your data variable. You could do all of that within your main function or do it separately and pass it to your function as a parameter.

ExtJS 5 Pie Chart Not Rendering Using Remote Store

I have a basic pie chart in ExtJS 5. The issue I am having is that the chart renders with a static JsonStore but won't render properly with a remote data.store?
Here is my code:
View (Chart)
Ext.define('APP.view.core.graphs.Countytotals', {
extend: 'Ext.Panel',
alias: 'widget.countytotalchart',
id: 'countyTotalsGraph',
width: 650,
initComponent: function() {
var me = this;
// Doesn't work?
var countyStore = Ext.create('APP.store.Countytotalsgraph');
// Works
var store = Ext.create('Ext.data.JsonStore', {
fields: ['COUNTY', 'AMOUNT'],
data: [{
'COUNTY': 'London',
'AMOUNT': 10.92
}, {
'COUNTY': 'Lancashire',
'AMOUNT': 6.61
}, {
'COUNTY': 'Kent',
'AMOUNT': 5.26
}, {
'COUNTY': 'West Yorkshire',
'AMOUNT': 4.52
}, {
'COUNTY': 'Nottinghamshire',
'AMOUNT': 4.01
}, {
'COUNTY': 'Other',
'AMOUNT': 68.68
}]
});
var chart = new Ext.chart.PolarChart({
width: '100%',
height: 500,
insetPadding: 50,
innerPadding: 20,
legend: {
docked: 'bottom'
},
listeners: {
afterrender: function (chart) {
if (chart.isVisible()) {
countyStore.load();
chart.redraw();
}
}
},
interactions: ['itemhighlight'],
store: countyStore,
series: [{
type: 'pie',
angleField: 'AMOUNT',
label: {
field: 'COUNTY',
display: 'outside',
calloutLine: {
length: 60,
width: 3
// specifying 'color' is also possible here
}
},
highlight: true,
tooltip: {
trackMouse: true,
renderer: function(storeItem, item) {
this.setHtml(storeItem.get('COUNTY') + ': ' + storeItem.get('AMOUNT') + '%');
}
}
}]
});
me.items = [chart];
this.callParent();
}
});
Store
Ext.define('APP.store.Countytotalsgraph', {
extend: 'Ext.data.Store',
model: 'APP.model.Countytotalsgraph',
autoLoad: false,
storeId: 'countyTotalsGraphStore',
proxy: {
type: 'ajax',
url : '/dashboard/countytotals',
method : 'POST',
reader: {
type: 'json',
rootProperty: 'data'
}
},
listeners: {
beforeload: function(store, eOpts) {
//if ( this.data.items.length ) {
//Ext.getCmp('optionsGrid').getView().refresh();
//}
store.proxy.extraParams = {
percentage: 'true'
}
}
}
});
Model
Ext.define('APP.model.Countytotalsgraph', {
extend: 'Ext.data.Model',
fields: ['COUNTY', 'AMOUNT']
});
This is how is renders with the static store:
This is how it renders with the remote store:
I am on the latest version of the GPL although the charts were built using Sencha CMD and the "sencha ant build" command in the sencha-charts directory.
Why does the static store display it (well still there is still an issue regarding the legend at the bottom) but the remote json not?
Iv'e tried to load the store after it the chart is rendered and is visible as I have seen a previous post regarding holding off on loading the store to give the chart time to render but this did not work:
listeners: {
afterrender: function (chart) {
if (chart.isVisible()) {
countyStore.load();
chart.redraw();
}
}
},
Thanks in advance :)
Nathan
Probably a bug in Ext.
The chart colors are set in Ext.chart.AbstractChart#updateColors. This is a "config" method, that is called automatically when setColors is called, and also from the constructor, when the config is initialized.
In your case, it is only called at construction time, before the remote store has been loaded; and it happens that polar series need to know the number of records in the store in order to know how many colors it must used (unlike other kind of charts that rely on number of axis or so).
Here's the code of that method:
updateColors: function (newColors) {
var me = this,
colors = newColors || (me.themeAttrs && me.themeAttrs.colors),
colorIndex = 0, colorCount = colors.length, i,
series = me.getSeries(),
seriesCount = series && series.length,
seriesItem, seriesColors, seriesColorCount;
if (colorCount) {
for (i = 0; i < seriesCount; i++) {
seriesItem = series[i];
// Ext.chart.series.Polar#themeColorCount uses store.getCount()
// so seriesColorCount will be 0
seriesColorCount = seriesItem.themeColorCount();
// ... hence seriesColor will be an empty array
seriesColors = me.circularCopyArray(colors, colorIndex, seriesColorCount);
colorIndex += seriesColorCount;
seriesItem.updateChartColors(seriesColors);
}
}
me.refreshLegendStore();
}
You could probably get it working by creating the chart after the load event of the store, but that's kind of kinky given your usage is as intended, and the bug will probably get smashed in a coming release.
For now, a possible fix is to override the onRefresh of the chart, that is called, well, when the store is refreshed, and force colors to be updated at this time:
Ext.define(null, {
override: 'Ext.chart.PolarChart'
,onRefresh: function() {
this.callParent(arguments);
var colors = this.getColors();
if (colors) {
this.updateColors(colors);
}
}
});

Treeview checkbox selection with graph updation is not working properly

In my project i have chart and treeview while pageload chart update is not working properly means here in treeview only two checkboxes are checked in pageload but chart is displaying all the field values.i need to display only checkbox checked field values in chart while pageload,( after page-load it's working fine).
here is the fiddle: http://jsfiddle.net/RHh67/64/
My chart code:
$("#myChart").kendoChart({
theme: $(document).data("kendoSkin") || "default",
dataSource: {
data: tmpData2,
sort: {
field: "date",
dir: "asc"
},
schema: {
model: {
fields: {
date: {
type: "date"
}
}
}
}
},
title: {
text: "My Date-aware Chart"
},
legend: {
position: "bottom"
},
seriesDefaults: {
type: "line",
labels: {
visible: true
},
missingValues: "gap"
},
series: series,
valueAxis: [{
name: "A",
labels: {
format: "{0}%"
}
},
{
name: "B",
labels: {
format: "{0}D"
}
}],
categoryAxis: {
type: "Date",
field: "date",
axisCrossingValue: [0, 1000]
}
});
Define a redrawChart that refreshes the Chart with the new series as:
function redrawChart() {
var chart = $("#myChart").data("kendoChart");
var checkedSeries = [];
$("#treeview").find(":checked").each(function () {
var nodeText = $(this).parent().parent().text();
$.each(series, function (index, series) {
if (series.field == nodeText) {
checkedSeries.push(series);
}
});
});
chart.options.series = checkedSeries;
chart.refresh();
}
This functions needs to be invoked:
On your tree change.
After setting the initial visible series.
In addition, move the selection of the initial series to the end of the JavaScript code. I mean, first initialize treeview and chart and only then initialize the initial values.
tree.dataItem(".k-item:nth(2)").set("checked", true);
tree.dataItem(".k-item:nth(3)").set("checked", true);
updateChks();
redrawChart();
The complete running version is in here http://jsfiddle.net/OnaBai/RHh67/68/

Categories

Resources