Pikaday.js : Uncaught RangeError: Maximum call stack size exceeded - javascript

I created a simple app which have table and chart with date filters. There's 4 choices. Today, Yesterday, This Month, and Last Month, and one Submit button. It's working perfectly when page load. The table show list all of model and the chart show data what I want expected, perfect.
When I choosed a choice (for example : This Month) and click submit for first time, table and chart is refreshing, perfect.
But when I choosed for second time, It's give me error, and page is freeze
pikaday.js:70 Uncaught RangeError: Maximum call stack size exceeded.
Here's my part code
chartView.on("form:filter", function(data){
var criterion = data
filteredData.filter(criterion)
data1 = filteredData.filter(criterion)
chartView.trigger("view:render");
})
Here's full part code
programming.module("Program.Chart",function(Chart, programming, Backbone, Marionette, $, _){
Chart.Controller = {
getData : function(){
var data1 = programming.request("data:entities");
if(data1 !== undefined){
var filteredData = programming.Program.FilteredCollection({
collection : data1,
filterFunction : function(criterion){
return function(data){
var dateModel = moment(data.get("tanggal"),'DD/MM/YYYY');
var startDate = moment(criterion.date1,'DD/MM/YYYY')
var endDate = moment(criterion.date2,'DD/MM/YYYY')
if(dateModel.isSameOrAfter(startDate)){
if(dateModel.isSameOrBefore(endDate)){
return data
}
}
}
}
})
chartView = new Chart.chartV({
collection: filteredData
})
chartView.on("form:filter", function(data){
var criterion = data
filteredData.filter(criterion)
data1 = filteredData.filter(criterion)
chartView.trigger("view:render");
})
chartView.on("view:render", function(){
//DatePicker
var format = "DD/MM/YYYY"
var date1 = new Pikaday({
field : $("#date1",this.el)[0],
format : format
})
$("#date1",this.el)[0].value = moment().add('days').format(format)
var date2 = new Pikaday({
field : $("#date2",this.el)[0],
format : format
})
$("#date2",this.el)[0].value = moment().add('days').format(format)
var selectdate = $('#publicdate',this.el)[0];
selectdate.addEventListener("change",function(){
var value = selectdate.value;
var date1 = $('#date1',this.el)[0];
var date2 = $('#date2',this.el)[0];
if(value==="today"){
date1.value = moment().add('days').format(format)
date2.value = moment().add('days').format(format)
$(date1).attr('disabled',true);
$(date2).attr('disabled',true);
} else if(value==="yesterday"){
date1.value = moment().add(-1,'days').format(format)
date2.value = moment().add(-1,'days').format(format)
$(date1).attr('disabled',true);
$(date2).attr('disabled',true);
} else if(value==="thismonth"){
date1.value = moment().add('month').startOf('month').format(format)
date2.value = moment().add('month').endOf('month').format(format)
$(date1).removeAttr('disabled',true);
$(date2).removeAttr('disabled',true);
} else if(value==="lastmonth"){
date1.value = moment().add(-1,'month').startOf('month').format('DD/MM/YYYY')
date2.value = moment().add(-1,'month').endOf('month').format('DD/MM/YYYY')
$(date1).attr('disabled',true);
$(date2).attr('disabled',true);
}
})
//Chartist JS
var labels = data1.models.map(function(model){
return model.get("tanggal");
})
var tshirtv = [];
var casev = [];
var tanggal = [];
var series = data1.models.map(function(model,index){
tanggal[index] = model.get("tanggal");
if(model.get("produk")==="T-Shirt"){
tshirtv[index] = model.get("jumlah");
casev[index] ="0";
} else if(model.get("produk")==="Case"){
casev[index] = model.get("jumlah");
tshirtv[index] ="0";
}
})
tshirtv = tshirtv.filter(()=>true)
casev = casev.filter(()=>true)
var series = [
{
name : "T-shirt",
data : tshirtv
},
{
name : "Case",
data : casev
}
]
//Line Chart
var data = {
labels : labels,
series : series
}
var option = {
showArea : true,
lineSmooth : false,
showPoint : true,
chartPadding : {
bottom:60,
top:60,
},
axisX : {
showGrid:false,
},
axisY : {
onlyInteger : true,
},
plugins : [
Chartist.plugins.ctAxisTitle({
axisX: {
axisClass: 'ct-axis-title',
offset: {
x: 0,
y: 50
},
textAnchor: 'middle'
},
axisY: {
axisTitle: 'Jumlah Penjualan',
axisClass: 'ct-axis-title',
offset: {
x: 0,
y: 0
},
textAnchor: 'middle',
flipTitle: false
}
}),
Chartist.plugins.ctPointLabels({
textAnchor : "middle"
}),
Chartist.plugins.legend()
]
}
//Donut Chart
var data2 = {
labels : ['T-Shirt', 'Case'],
series : [12,23]
}
var option2 = {
chartPadding : {
top : 0,
},
labelInterpolationFnc : function(value,series){
return value + ": " +data2.series[series].value
},
donut:true,
donutWidth : 60,
plugins : [
Chartist.plugins.legend()
]
}
new Chartist.Line($('.statistic',this.el)[0],data,option)
//new Chartist.Pie($('.statistic2',this.el)[0],data2,option2)
})
programming.wrapper.show(chartView)
} else {
chartView = new Chart.notfound()
programming.wrapper.show(chartView)
}
}
}
})

Related

Why highchart returning " Typeerror : undefined variable byte "?

I am trying to draw a graph with the help of high chart and also using load event I am trying to add values after each 1 second to the graph.
In this graph I also want to show axis as Mb,Kb,,Gb data. So I am writing a function to return the byte values as Mb,Kb,Gb (for both series and tooltip)
This is my code :
// highchart options :
var series1, series2 ;
var chart = {
type: 'bar',
events: {
load: function () {
// set up the updating of the chart each second
series1 = this.series[0];
series2 = this.series[1];
setInterval(function () {
add_function();
}, 1000);//call function each 1 second
}
}
};
var tooltip = {
enabled: true,
formatter: function() { return fbytes(this.y,2);}
};
var plotOptions = {
bar: {
},
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
pointPadding: 0,
pointWidth:38
},
column : {
grouping: true
}
};
series= [
{
name: 'old',
color: '#f9a80e',
data: [,]
},
{
name: 'new',
color: '#89897f',
data: [,]
}
];
and the load event function is :
Array.max = function (array) {
return Math.max.apply(Math, array);
};
Array.min = function (array) {
return Math.min.apply(Math, array);
};
add_function()
{
var arr[];
//getting array values here
var min_value = Array.min(arr);
var max_value = Array.max(arr);
var chart2 = $('#container').highcharts();
chart2.yAxis[0].update({max:max_value, min: 0}, true);
series1.setData([arr[0],arr[2]], true, true);
series2.setData([arr[1],arr[3]], true, true);
}
and the conversion function :
function fbytes(bytes, precision) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
var posttxt = 0;
if (bytes == 0) return '0 Bytes';
if (bytes < 1024) {
return Number(bytes) + " " + sizes[posttxt];
}
while( bytes >= 1024 ) {
posttxt++;
bytes = bytes / 1024;
}
return Math.round(bytes.toPrecision(precision)) + " " + sizes[posttxt];
}
my logic : i got some array values randomly and i am displaying this data on the graph .
problem facing : I didn't get this.y value inside series . When i print this value inside
series: {
dataLabels: {
enabled: true,
formatter: function() { return fbytes(this.y,2);},
inside: true,
style: {fontWeight: 'number'}
},
I am getting this.y = undefined . What is happening ?
Any mistake in the code ? Any suggestions ?
I created demo using your code and modified add_function() a little bit. Did you mean something like this?
function add_function(series1, series2) {
var chart2 = $('#container').highcharts(),
increment = 1024,
min_value,
max_value,
newVal1 = [],
newVal2 = [];
if (!series1.data.length && !series2.data.length) {
var arr = [512, 128, 1024, 0];
min_value = Array.min(arr);
max_value = Array.max(arr);
newVal1 = [arr[0], arr[2]];
newVal2 = [arr[1], arr[3]];
} else {
series1.yData.forEach(function(sEl, sInx) {
newVal1.push(sEl + increment);
});
series2.yData.forEach(function(sEl, sInx) {
newVal2.push(sEl + increment);
});
max_value = Array.max(newVal1.concat(newVal2));
}
chart2.yAxis[0].update({
max: max_value,
min: 0
}, true);
series1.setData(newVal1, true, true);
series2.setData(newVal2, true, true);
}
Example:
http://jsfiddle.net/js3g311q/

Set a full background color to the canvas in chartjs 2.0

Basically my question is similar to the one asked here How to set a full length background color for each bar in chartjs bar
It has a desired jsfiddle link http://jsfiddle.net/x73rhq2y/
But it does not work for chartjs 2.* (I am using chart.min.bundle.js v2.1.6)
I am trying to extend my bar chart to display multiple stacked bar chart. Along with it I need to separate out the bar chart background.
Chart.defaults.groupableBar = Chart.helpers.clone(Chart.defaults.bar);
var helpers = Chart.helpers;
Chart.controllers.groupableBar = Chart.controllers.bar.extend({
calculateBarX: function (index, datasetIndex) {
// position the bars based on the stack index
var stackIndex = this.getMeta().stackIndex;
return Chart.controllers.bar.prototype.calculateBarX.apply(this, [index, stackIndex]);
},
hideOtherStacks: function (datasetIndex) {
var meta = this.getMeta();
var stackIndex = meta.stackIndex;
this.hiddens = [];
for (var i = 0; i < datasetIndex; i++) {
var dsMeta = this.chart.getDatasetMeta(i);
if (dsMeta.stackIndex !== stackIndex) {
this.hiddens.push(dsMeta.hidden);
dsMeta.hidden = true;
}
}
},
unhideOtherStacks: function (datasetIndex) {
var meta = this.getMeta();
var stackIndex = meta.stackIndex;
for (var i = 0; i < datasetIndex; i++) {
var dsMeta = this.chart.getDatasetMeta(i);
if (dsMeta.stackIndex !== stackIndex) {
dsMeta.hidden = this.hiddens.unshift();
}
}
},
calculateBarY: function (index, datasetIndex) {
this.hideOtherStacks(datasetIndex);
var barY = Chart.controllers.bar.prototype.calculateBarY.apply(this, [index, datasetIndex]);
this.unhideOtherStacks(datasetIndex);
return barY;
},
calculateBarBase: function (datasetIndex, index) {
this.hideOtherStacks(datasetIndex);
var barBase = Chart.controllers.bar.prototype.calculateBarBase.apply(this, [datasetIndex, index]);
this.unhideOtherStacks(datasetIndex);
return barBase;
},
getBarCount: function () {
var stacks = [];
// put the stack index in the dataset meta
Chart.helpers.each(this.chart.data.datasets, function (dataset, datasetIndex) {
var meta = this.chart.getDatasetMeta(datasetIndex);
if (meta.bar && this.chart.isDatasetVisible(datasetIndex)) {
var stackIndex = stacks.indexOf(dataset.stack);
if (stackIndex === -1) {
stackIndex = stacks.length;
stacks.push(dataset.stack);
}
meta.stackIndex = stackIndex;
}
}, this);
this.getMeta().stacks = stacks;
return stacks.length;
},
initialize: function (data) {
debugger;
var self = data;
var originalBuildScale = self.buildScale;
self.buildScale = function () {
originalBuildScale.apply(this, arguments);
debugger;
var ctx = self.chart.ctx;
var scale = self.scale;
var originalScaleDraw = self.scale.draw;
var barAreaWidth = scale.calculateX(1) - scale.calculateX(0);
var barAreaHeight = scale.endPoint - scale.startPoint;
self.scale.draw = function () {
originalScaleDraw.call(this, arguments);
scale.xLabels.forEach(function (xLabel, i) {
ctx.fillStyle = data.labelBackgrounds[i];
ctx.fillRect(
scale.calculateX(i - (scale.offsetGridLines ? 0.5 : 0)),
scale.startPoint,
barAreaWidth,
barAreaHeight);
ctx.fill();
});
};
};
Chart.controllers.bar.prototype.initialize.apply(this, arguments);
}
});
But since the documentation has been updated , i am not able to find the solution.
My data Array is as follows:
var data = {
labels: ["Label1","Label2","Label2","Label2",],
labelBackgrounds: ["rgba(120,220,220,0.2)", "rgba(220,120,220,0.2)", "rgba(220,220,120,0.2)", "rgba(120,120,220,0.2)"],
datasets: [
{
label: "Pass",
backgroundColor: "rgba(3,166,120,0.7)",
data: [40,50,30,45],
stack: 1
},
{
label: "Fail",
backgroundColor: "rgba(212,82,84,0.7)",
data: [40,50,30,45],
stack: 1
},
{
label: "Not run",
backgroundColor: "rgba(89,171,227,0.7)",
data: [40,50,30,45],
stack: 1
},
{
label: "Pass",
backgroundColor: "rgba(3,166,120,0.7)",
data: [40,50,30,45],
stack: 2
},
{
label: "Fail",
backgroundColor: "rgba(212,82,84,0.7)",
data: [40,50,30,45],
stack: 2
},
{
label: "Not run",
backgroundColor: "rgba(89,171,227,0.7)",
data: [40,50,30,45],
stack: 2
}
]
};
P.S: I had to create a new question as my reputation does not allows me to comment on https://stackoverflow.com/a/31833017/4787971

highcharts-ng ajax data load

I have the following HTTP request that i use to fill out my chart:
$scope.series = ['Moduler tager', 'Gns.score'];
$scope.activity_data = [];
$scope.activity_ticks = [];
var tmp_data = [];
$scope.bar = [];
$scope.line = [];
$http.get(api.getUrl('findSelfActivityByDivisions', null))
.success(function (response) {
response.forEach(function(y){
var i = 0;
var log_date = y.date.substr(0, y.date.indexOf('T'));
var date = new Date(log_date);
var logg_date = moment(date).fromNow();
var indexOf = tmp_data.indexOf(logg_date);
var found = false;
var index = 0;
if(tmp_data.length > 0){
tmp_data.forEach(function(current_data){
if(current_data[0] == logg_date){
found = true;
}
if(!found){
index++;
}
})
}
if(found){
var tmp = tmp_data[index];
tmp[1] = tmp[1] + y.num_modules;
tmp[2] = tmp[2] + y.num_score_modules;
tmp[3] = tmp[3] + y.sum_score;
tmp_data[index] = tmp;
}
else
{
var tmp = [logg_date, y.num_modules, y.num_score_modules, y.sum_score];
tmp_data.push(tmp);
}
})
var line = [];
var bar = [];
tmp_data.forEach(function(data){
$scope.activity_ticks.push(data[0])
line.push(data[1]);
var avg_score = data[3] / data[2];
if(isNaN(avg_score)){
avg_score = 0;
}
bar.push(avg_score);
});
$scope.line = line;
$scope.bar = bar;
});
Now then i have the following chart config:
$scope.chartConfig = {
options: {
chart: {
type: 'areaspline'
}
},
series: [{
data: $scope.bar,
type: 'column'
},{
data: $scope.line,
type: 'line'
}],
xAxis: {
categories: $scope.activity_ticks
},
title: {
text: 'Hello'
},
loading: false
}
Sadly none of the graphs are showing (im guessing it has something to do with the date comming after the load)
Can anyone help me out?
Your $scope.chartConfig is likely firing before the success callback of your $http.get(api.getUrl('findSelfActivityByDivisions', null)) completes. I am assuming $scope.chartConfig is located in a controller. Try placing a $watchGroup on the values then apply your chart rendering logic once those values resolve. An example may include
Note that $watchGroup is found within Angular as of 1.3
$scope.$watchGroup(['line', 'bar'], function(newValues, oldValues) {
// newValues[0] --> $scope.line
// newValues[1] --> $scope.bar
if(newValues !== oldValues) {
$scope.chartConfig = {
options: {
chart: {
type: 'areaspline'
}
},
series: [{
data: $scope.bar,
type: 'column'
},{
data: $scope.line,
type: 'line'
}],
xAxis: {
categories: $scope.activity_ticks
},
title: {
text: 'Hello'
},
loading: false
}
}
});

In jqxGrid, how do I add a new calculated column from JSON data?

In jqxGrid, how do I add a new calculated column from JSON data?
My JSON data has fields baseQuantity and unitCost. I want to add a new field called totalCost which would be baseQuantity * unitCost.
I'm trying to add the data using loadComplete, but it doesn't seem to work.
ANOTHER alternative I could do is to loop through objData and inject a new field with the calculated value. But aside from that, is there any way I could do it via jqxGrid's API?
var jsonString = [{ "baseQuantity":"1", "unitCost":"2"}, { "baseQuantity":"3", "unitCost":"4"}];
var objData = $.parseJSON(jsonString);
var srcData = {
datatype: "json",
datafields: [
{ name : 'baseQuantity', type : 'number' },
{ name : 'unitCost', type : 'number' }
],
localdata : objData
};
var adapterData = new $.jqx.dataAdapter(srcData, {
loadComplete: function (records) {
var modifiedDataArray = new Array();
for (var i = 0; i < records.length; i++) {
var modifiedData = records[i];
modifiedData.totalPayment = modifiedData.baseQuantity * modifiedData.unitCost;
modifiedDataArray.push(programme);
}
return modifiedDataArray;
}
});
$('div#jqxGrid').jqxGrid({
width: '100%',
source: adapterData,
theme: getTheme(),
pageable: true,
autoheight: true,
sortable: true,
altrows: true,
columns: [
{ datafield: 'baseQuantity', text: 'Base Qty.', width: 120 }
{ datafield: 'unitCost', text: 'Unit Payment' , width: 120 }
]
});
Use the cellrenderer function:
http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-api.htm
{ text: 'totalCost', datafield: 'totalCost', width: 70, cellsalign: 'right', columntype: 'number',
cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
var rowData = $("#jqxGrid").jqxGrid('getrowdata', row);
return rowData.baseQuantity * rowData.unitCost;
}
}
Don't use the event "loadComplete" but "beforeLoadComplete" instead. Here is an example :
var dataAdapter = new $.jqx.dataAdapter(source,
{
beforeLoadComplete: function (records) {
records[0]['firstname'] = "Michael";
return records;
}
}
);
Than you can loop through all records, and generate you computed column. This is the official solution they seems to give here : http://www.jqwidgets.com/community/topic/computed-column/

get json data from my controller in highcharts.js

I am trying to make a highchart which should show me number of reserved rooms for every type:
Here is my controller with GetHighChart method:
public JsonResult GetHighChart()
{
var viewModel = Reservation.RoomTypeByDate(5);
var result = new JsonResult { Data = viewModel};
return result;
}
Reservetion.RoomTypeByDate looks like this:
public static List<dynamic> RoomTypeByDate(int? LunaDorita)
{
var result=DBContext.Current.ExecuteProcedure("RoomtypeCountbydate",
new QueryParam<int>("#p_ID", LunaDorita.Value)).Map();
return result;
And here is my stored procedure:
SELECT Room_Type, COUNT(*) AS NumarRezervari
FROM dbo.Reservation re
JOIN dbo.Room ro ON ro.RoomID = re.Room_ID
JOIN dbo.Room_Type rt ON rt.RoomType_ID = ro.Room_Type_ID
WHERE MONTH(re.Data_Check_in)=#p_ID
GROUP BY Room_Type
My Json Result is:
[[{"Key":"Room_Type","Value":"Double"},{"Key":"NumarRezervari","Value":2}], [{"Key":"Room_Type","Value":"LUXURY"},{"Key":"NumarRezervari","Value":1}],[{"Key":"Room_Type","Value":"Triple"},{"Key":"NumarRezervari","Value":1}]]
How should I modify this javascript file so that instead of the series from below to have my data from my GetHighChart method from myReports controler.So instead of name i want to have my RoomType for example Double and instead of data to have my own data [2,5....]?
$(function () {
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Monthly Average Temperature'
},
subtitle: {
text: 'Source: WorldClimate.com'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Temperature (°C)'
}
},
tooltip: {
enabled: false,
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y + '°C';
}
},
plotOptions: {
line: {
dataLabels: {
enabled: true
},
enableMouseTracking: false
}
},
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}, {
name: 'London',
data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]
});
});
});
If you are using Visual Studio you can use DotNet.Highcharts to make building highchart objects much easier. By doing so you can work with Series and Data objects directly and then just pass them into Highcharts. It takes the creation of the JavaScript out of the picture. Below is a sample of how I create my charts in MVC 3. As you can see I am using LINQ to SQL to gather the required data for the chart. I am creating a list of Series to hold the data. This is done dynamically so I can add as many Series as needed for the chart without having to know how many there will be beforehand. Then I create the chart and pass the list of Series to it.
public ActionResult CombinerBarToday(DateTime? utcStartingDate = null,
DateTime? utcEndingDate = null)
{
//GET THE GENERATED POWER READINGS FOR THE SPECIFIED DATETIME
var firstQ = from s in db.PowerCombinerHistorys
join u in db.PowerCombiners on s.combiner_id equals u.id
where s.recordTime >= utcStartingDate
where s.recordTime <= utcEndingDate
select new
{
CombinerID = u.name,
Current = s.current,
RecordTime = s.recordTime,
Voltage = s.voltage,
Watts = (s.current * s.voltage)
};
//GET A LIST OF THE COMBINERS CONTAINED IN THE QUERY
var secondQ = (from s in firstQ
select new
{
Combiner = s.CombinerID
}).Distinct();
/* THIS LIST OF SERIES WILL BE USED TO DYNAMICALLY ADD AS MANY SERIES
* TO THE HIGHCHARTS AS NEEDED WITHOUT HAVING TO CREATE EACH SERIES INDIVIUALY */
List<Series> allSeries = new List<Series>();
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
//LOOP THROUGH EACH COMBINER AND CREATE SERIES
foreach (var distinctCombiner in secondQ)
{
var combinerDetail = from s in db2.PowerCombinerHistorys
join u in db2.PowerCombiners on s.combiner_id equals u.id
where u.name == distinctCombiner.Combiner
where s.recordTime >= utcStartingDate
where s.recordTime <= utcEndingDate
select new
{
CombinerID = u.name,
Current = s.current,
RecordTime = s.recordTime,
Voltage = s.voltage,
Watts = (s.current * s.voltage) / 1000d
};
var results = new List<object[]>();
foreach (var detailCombiner in combinerDetail)
{
results.Add(new object[] {
TimeZoneInfo.ConvertTimeFromUtc(detailCombiner.RecordTime, easternZone),
detailCombiner.Watts });
}
allSeries.Add(new Series
{
Name = distinctCombiner.Combiner,
//Data = new Data(myData)
Data = new Data(results.ToArray())
});
}
Highcharts chart = new Highcharts("chart")
.InitChart(new Chart { DefaultSeriesType = ChartTypes.Spline, ZoomType = ZoomTypes.X})
.SetTitle(new Title { Text = "Combiner History" })
.SetSubtitle(new Subtitle { Text = "Click and drag in the plot area to zoom in" })
.SetOptions(new GlobalOptions { Global = new Global { UseUTC = false } })
.SetPlotOptions(new PlotOptions
{
Spline = new PlotOptionsSpline
{
LineWidth = 2,
States = new PlotOptionsSplineStates { Hover = new PlotOptionsSplineStatesHover { LineWidth = 3 } },
Marker = new PlotOptionsSplineMarker
{
Enabled = false,
States = new PlotOptionsSplineMarkerStates
{
Hover = new PlotOptionsSplineMarkerStatesHover
{
Enabled = true,
Radius = 5,
LineWidth = 1
}
}
}
}
})
.SetXAxis(new XAxis
{
Type = AxisTypes.Datetime,
Labels = new XAxisLabels
{
Rotation = -45,
Align = HorizontalAligns.Right,
Style = "font: 'normal 10px Verdana, sans-serif'"
},
Title = new XAxisTitle { Text = "Time(Hour)" },
})
.SetYAxis(new YAxis
{
Title = new YAxisTitle { Text = "Kilowatt" }
})
.SetSeries(allSeries.Select(s => new Series {Name = s.Name, Data = s.Data }).ToArray());
return PartialView(chart);
}
Follow the following steps:
Make chart a global variable
var chart;
You can define load event to your chart like this
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 10,
events: {
load: requestData
}
}
}
here requestData is a javascript function. In this function you can bind data dynamically to the chart.
function requestData() {
var pointArray = [];
for (var i = 0; i < data2.length; i++) {
// var series, shift;
// var point = new Array(new Date(data2[i].UTC).getTime(), parseFloat(data2[i].Value));
var point = {
x: new Date(data2[i].UTC).getTime(),
y: parseFloat(data2[i].Value)
};
chartRTM.series[0].addPoint(point);
}
chartRTM.series[0].redraw();}
NOTE: Here data2 is a json list of the data to be bound.

Categories

Resources