Adding Context to Django View Causing My Highcharts Map to Disappear - javascript

This is my first Django project, and I am working on a Django html template that should contain a Chart.JS bar graph (https://www.chartjs.org/docs/latest/charts/bar.html) alongside a Highcharts drilldown map of the US (https://www.highcharts.com/demo/maps/map-drilldown).
I've successfully implemented my Chart.JS bar graph and passed data to it from our AWS RDS. But now when I try to implement even just the stock Highcharts code from their website, the map fails to render at all. After trying to isolate the problem, I've found that the map does render if I simply delete "context" from the return statement in my view (i.e. delete "context" from the final line in my first block of code below). But this obviously then inhibits my bar graph from rendering. I think I must be missing something with how the highcharts data is loaded in the presence of other context data, but I've been unable to fix it such that both the graph and map render. Any help would be greatly appreciated!
My Django View:
def index(request):
mydb = mysql.connector.connect(
host=xxxx,
user=xxxx,
password=xxxx,
database=xxxx
)
mycursor = mydb.cursor()
mycursor.execute("WITH CS1 AS (SELECT cts.Name, cts.State, m.Frequently, m.Always FROM Masks m JOIN Counties cts ON (m.FIPS = cts.FIPS)) SELECT CS1.State, AVG((CS1.Frequently+CS1.Always)*100) AS Perc_High_Frequency FROM CS1 WHERE CS1.State<>'Puerto Rico' GROUP BY CS1.State ORDER BY Perc_High_Frequency DESC")
tempList = mycursor.fetchall()
statesMaskName = [item[0] for item in tempList]
statesMaskPerc = [item[1] for item in tempList]
context={'statesMaskName':statesMaskName, 'statesMaskPerc':statesMaskPerc}
return render(request,'index.html', context)
The relevant HTML/JS:
<html lang="en" dir="ltr">
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="fixed-header">
<h1>COVID-19 Sentiment and Mask Practices</h1>
</div>
<div>
<div class="col-lg-3" style="float: left; max-height: 6500px;max-width:400px;overflow: scroll; overflow-x:hidden;">
<div style="background-color: #17202A;">
<span style="color: #F7F9F9; text-align: center;"><h4>% Population Who "Frequently" or "Always" Wear Masks When In Public Within 6" of Others (as of July 2-14, 2020)</h4></span>
</div>
<div class="col-lg-12">
<form method="post" enctype="multipart/form-data" action="selectState">
{% csrf_token %}
<div class="col-lg-4" style="float: left; max-height: 3000px;">
<br><br style="line-height: 15px"/>
{% for state in statesMaskName %}
<table style="border-width: 2px; border: #333;">
<tr>
<input type="submit" value="{{state}}" name="statesMaskName" style="width:130px;">
</tr>
</table>
{% endfor%}
</div>
<div style="float: left;">
<canvas id="myChart" height="1360" width="250"></canvas>
</div>
</form>
</div>
</div>
<div class="col-lg-6">
</div>
<div class="col-lg-3">
</div>
</div>
<br>
</body>
<!--my updated code for chartjs graph-->
<script>
const labels = {{statesMaskName|safe}};
const data = {
labels: labels,
datasets: [{
label: '% Population',
color: 'orange',
backgroundColor: 'orange',
borderColor: 'orange',
data: {{statesMaskPerc|safe}},
}]
};
const config = {
type: 'bar',
data,
options: {
indexAxis: 'y',
color: 'white',
scales: {
y: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
},
display: false
},
x: {
grid: {
color: '#b3b1ad',
},
ticks: {
color: 'white',
// Include a % sign in the ticks
callback: function(value, index, values) {
return value + '%';
}
}
}
}
}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
<!--stock code for highcharts map-->
<div id="usMap" style="height: 500px; min-width: 310px; max-width: 800px; margin: 0 auto"></div>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/data.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="https://code.highcharts.com/maps/modules/offline-exporting.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
<script type="text/javascript">
/*
TODO:
- Check data labels after drilling. Label rank? New positions?
*/
let data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']);
const separators = Highcharts.geojson(Highcharts.maps['countries/us/us-all'], 'mapline');
// Set drilldown pointers
data.forEach((d, i) => {
d.drilldown = d.properties['hc-key'];
d.value = i; // Non-random bogus data
});
function getScript(url, cb) {
const script = document.createElement('script');
script.src = url;
script.onload = cb;
document.head.appendChild(script);
}
// Instantiate the map
Highcharts.mapChart('usMap', {
chart: {
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
const chart = this,
mapKey = 'countries/us/' + e.point.drilldown + '-all';
// Handle error, the timeout is cleared on success
let fail = setTimeout(() => {
if (!Highcharts.maps[mapKey]) {
chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
fail = setTimeout(() => {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner
// Load the drilldown map
getScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', () => {
data = Highcharts.geojson(Highcharts.maps[mapKey]);
// Set a non-random bogus value
data.forEach((d, i) => {
d.value = i;
});
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
});
}
this.setTitle(null, { text: e.point.name });
},
drillup: function () {
this.setTitle(null, { text: '' });
}
}
},
title: {
text: 'Highcharts Map Drilldown'
},
subtitle: {
text: '',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series: [{
data: data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}, {
type: 'mapline',
data: separators,
color: 'silver',
enableMouseTracking: false,
animation: {
duration: 500
}
}],
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
</script>
</html>

Related

Make highcharts fullscreen also fullscreen the div wrapping the chart

Is there a way to make the div wrapping the chart part of the fullscreen as well?
This is my code: fiddle
THis code only fulscreens the chart. When I try and do to point the div I need in the fullscreen:
Highcharts.FullScreen = function(container) {
this.init(ontainer.parentNode.parentNode);
};
My fullscreen is getting cut off and also not adding the parent div to the full screen. Is there to make the whole div with id yo and the other div inside (<div>Random Data and text.......</div>) as part of the fullscreen?
You can connect the content of a custom element through chart.renderer.text().add() by specifying this element with the html() method:
chart.renderer.text(selector.html(), 0, 0).add();
...hiding this element through css, set the display: none:
.random_data {
display: none;
}
This is the piece of code to add:
function (chart) {
chart.renderer
.text($(".random_data").html(), 10, 10)
.css({
color: "green",
fontSize: "12px",
})
.add();
}
JavaScript:
let chart = Highcharts.chart(
"container",
{
chart: {
type: "column",
},
title: {
text: "",
},
xAxis: {
categories: ["one", "two", "three"],
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0,
},
},
yAxis: {
title: {
text: "",
},
endOnTick: false,
},
series: [
{
name: "books",
data: [
["one", 64161.71548379661],
["two", 3570.6197029028076],
["three", -200.70625619033547],
],
marker: {
symbol: "circle",
},
},
],
},
function (chart) {
chart.renderer
.text($(".random_data").html(), 10, 10)
.css({
color: "green",
fontSize: "12px",
})
.add();
}
);
let btn = document.getElementById("btn");
btn.addEventListener("click", function () {
Highcharts.FullScreen = function (container) {
console.log(container.parentNode.parentNode);
this.init(container.parentNode); // main div of the chart
};
Highcharts.FullScreen.prototype = {
init: function (container) {
if (container.requestFullscreen) {
container.requestFullscreen();
} else if (container.mozRequestFullScreen) {
container.mozRequestFullScreen();
} else if (container.webkitRequestFullscreen) {
container.webkitRequestFullscreen();
} else if (container.msRequestFullscreen) {
container.msRequestFullscreen();
}
},
};
chart.fullscreen = new Highcharts.FullScreen(chart.container);
});
CSS:
.random_data {
display: none;
}
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="yo">
<div class="random_data">Random Data and text.......</div>
<div id="container" style="height: 400px; margin-top: 1em;"></div>
</div>
<button id="btn">
Show full screen
</button>

Chart.js Chart does not start at

I want to that the Chart start at 0. But it takes always the lower value to start.
I already tried a few things but nothing works.
It never takes the settings done in de options Part of de javascript part. So i dont know what the issue is. It never starts at 0. But this is what i want to.
Please help. Thank you very much :)
Looks currently like this: https://school.luis-luescher.com/m242/moin/index.php
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<style type="text/css">
BODY {
width: 550PX;
}
#chart-container {
width: 100%;
height: auto;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
</head>
<body>
<div id="chart-container">
<canvas id="graphCanvas"></canvas>
</div>
<script>
$(document).ready(function() {
showGraph();
});
function showGraph() {
{
$.post("https://school.luis-luescher.com/m242/moin/data.php",
function(data) {
console.log(data);
var trytime = [];
var count = [];
for (var i in data) {
trytime.push(data[i].trytime);
count.push(data[i].count);
}
var chartdata = {
labels: trytime,
datasets: [{
label: 'Erfolgreiche Authentifizerungen',
backgroundColor: '#8846f1',
borderColor: '#a446f1',
hoverBackgroundColor: '#CCCCCC',
hoverBorderColor: '#666666',
borderWidth: 1,
data: count,
}],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
var graphTarget = $("#graphCanvas");
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata
});
});
}
}
</script>
</body>
</html>
Your Options object must be outside chartData.
var barGraph = new Chart(graphTarget, {
type: 'bar',
data: chartdata,
options: options
});

Is it possible to use mouseenter and mouseleave event in chart js?

Right now I'm using onHover into each pie to add some scale/zoom, but I want to use mouseenter and mouseleave. So on mouseenter on each pie it will add some scale/zoom, and on mouseleave, I want it back to its original state.
either mouseenter-mouseleave or mouseover-mouseout is fine.
here is the codepen:
https://codepen.io/graydirt/pen/NWNZNyQ
Thanks guys!
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function (evt, elements) {
let segment;
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>
Your code is already designed to return to the original size on mouseout, but you have a subtle bug.
You need to define the segment variable outside the chart. With a saved reference to the segment, the mouseout event will fire and the onHover handler will return the pie to its original size.
Please see the attached example below:
let segment;
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['Red', 'Blue', 'Green'],
datasets: [{
label: '# of Votes',
data: [12, 19, 20],
backgroundColor: [
'red',
'blue',
'green'
],
datalabels: {
color: '#000'
}
}]
},
options: {
legend: {
display: false
},
layout: {
padding: 5
},
onHover: function(evt, elements) {
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 5;
} else {
if (segment) {
segment._model.outerRadius -= 5;
}
segment = null;
}
}
}
});
.chart-pie {
width: 400px;
height: 400px;
margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.7.0"></script>
<div class="container p-4">
<div class="chart-pie position-relative">
<canvas id="chartPie"></canvas>
</div>
</div>

Highcharts maps with decimals

I try to replicate this example file of highcharts with a different kind of data file. In the new database, life expectancy per country is 13 decimal places. The source is also world bank, which makes the structure comparable. Here is the example JSFIDDLE. Unfortunately, this does not work because presumably "numRegex = /^[0-9.]+$/" on line 26 is wrong. Unfortunately I have no idea what should be put here.
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/maps/modules/map.js"></script>
<script src="https://code.highcharts.com/mapdata/custom/world.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css">
<!-- Flag sprites service provided by Martijn Lafeber, https://github.com/lafeber/world-flags-sprite/blob/master/LICENSE -->
<link rel="stylesheet" type="text/css" href="//github.com/downloads/lafeber/world-flags-sprite/flags32.css" />
<div class="container_fluid">
<div class="row">
<div class="col-lg-12 col-md-12">
<div class="panel color-orange shadow">
<div class="panel-heading text-white text-center">
</div>
<div class="panel-body color-grey text-center">
<div class="col-lg-12 col-md-12 position-padding-ver position-padding-hor">
<div id="wrapper_landkaart">
<div id="container"></div>
<div id="info">
<span class="f32"><span id="flag"></span></span>
<h2></h2>
<div class="subheader">Click countries to view history</div>
<div id="country-chart"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScript
$.ajax({
url: 'https://cdn.filestackcontent.com/WZkkd6c4S3euwmgoV88v',
success: function(csv) {
// Parse the CSV Data
/*Highcharts.data({
csv: data,
switchRowsAndColumns: true,
parsed: function () {
console.log(this.columns);
}
});*/
// Very simple and case-specific CSV string splitting
function CSVtoArray(text) {
return text.replace(/^"/, '')
.replace(/",$/, '')
.split('","');
}
csv = csv.split(/\n/);
var countries = {},
mapChart,
countryChart,
numRegex = /^[0-9\.]+$/,
lastCommaRegex = /,\s$/,
quoteRegex = /\"/g,
categories = CSVtoArray(csv[2]).slice(4);
// Parse the CSV into arrays, one array each country
$.each(csv.slice(3), function(j, line) {
var row = CSVtoArray(line),
data = row.slice(4);
$.each(data, function(i, val) {
val = val.replace(quoteRegex, '');
if (numRegex.test(val)) {
val = parseInt(val, 10);
} else if (!val || lastCommaRegex.test(val)) {
val = null;
}
data[i] = val;
});
countries[row[1]] = {
name: row[0],
code3: row[1],
data: data
};
});
// For each country, use the latest value for current population
var data = [];
for (var code3 in countries) {
if (countries.hasOwnProperty(code3)) {
var value = null,
year,
itemData = countries[code3].data,
i = itemData.length;
while (i--) {
if (typeof itemData[i] === 'number') {
value = itemData[i];
year = categories[i];
break;
}
}
data.push({
name: countries[code3].name,
code3: code3,
value: value,
year: year
});
}
}
// Add lower case codes to the data set for inclusion in the tooltip.pointFormat
var mapData = Highcharts.geojson(Highcharts.maps['custom/world']);
$.each(mapData, function() {
this.id = this.properties['hc-key']; // for Chart.get()
this.flag = this.id.replace('UK', 'GB').toLowerCase();
});
// Wrap point.select to get to the total selected points
Highcharts.wrap(Highcharts.Point.prototype, 'select', function(proceed) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
var points = mapChart.getSelectedPoints();
if (points.length) {
if (points.length === 1) {
$('#info #flag').attr('class', 'flag ' + points[0].flag);
$('#info h2').html(points[0].name);
} else {
$('#info #flag').attr('class', 'flag');
$('#info h2').html('Comparing countries');
}
$('#info .subheader').html('<h4>Historical population</h4><small><em>Shift + Click on map to compare countries</em></small>');
if (!countryChart) {
countryChart = Highcharts.chart('country-chart', {
chart: {
height: 250,
spacingLeft: 0
},
credits: {
enabled: false
},
title: {
text: null
},
subtitle: {
text: null
},
xAxis: {
tickPixelInterval: 50,
crosshair: true
},
yAxis: {
title: null,
opposite: true
},
tooltip: {
split: true
},
plotOptions: {
area: {
color: '#fa7921'
},
series: {
animation: {
duration: 500
},
marker: {
enabled: false
},
threshold: 0,
pointStart: parseInt(categories[0], 10)
}
}
});
}
$.each(points, function(i) {
// Update
if (countryChart.series[i]) {
/*$.each(countries[this.code3].data, function (pointI, value) {
countryChart.series[i].points[pointI].update(value, false);
});*/
countryChart.series[i].update({
name: this.name,
data: countries[this.code3].data,
type: points.length > 1 ? 'line' : 'area'
}, false);
} else {
countryChart.addSeries({
name: this.name,
data: countries[this.code3].data,
type: points.length > 1 ? 'line' : 'area'
}, false);
}
});
while (countryChart.series.length > points.length) {
countryChart.series[countryChart.series.length - 1].remove(false);
}
countryChart.redraw();
} else {
$('#info #flag').attr('class', '');
$('#info h2').html('');
$('#info .subheader').html('');
if (countryChart) {
countryChart = countryChart.destroy();
}
}
});
// Initiate the map chart
mapChart = Highcharts.mapChart('container', {
title: {
text: 'Population history by country'
},
subtitle: {
text: 'Source: The World Bank'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
colorAxis: {
type: 'logarithmic',
endOnTick: false,
startOnTick: false,
minColor: '#9E90B3',
maxColor: '#3D1C5C',
min: 50000
},
tooltip: {
footerFormat: '<span style="font-size: 10px">(Click for details)</span>'
},
series: [{
data: data,
mapData: mapData,
joinBy: ['iso-a3', 'code3'],
name: 'Current population',
allowPointSelect: true,
cursor: 'pointer',
states: {
select: {
color: '#D06918',
borderColor: 'black',
dashStyle: 'shortdot'
}
}
}]
});
// Pre-select a country
mapChart.get('us').select();
}
});
Hopefully someone can help me further on this. Thank you very much.
Your CSV file is broken it looks like this:
"Data Source,""World Development Indicators"","
it should look like
"Data Source","World Development Indicators",
CSV won't split on a , if it's in quotes hence you can include comma's in your file as text if you include them in quotes.
Fix your CSV file and it should work.

Add a dropdown to Highcharts to change chart type with AngularJs

So I am trying to create a drop-down list that will turn my HighCharts from a bar chart to a pie graph whenever the user picks their selection I am positive I have the right code but I keep getting this error: Cannot read property 'series' of undefined I have gone though a dozen examples but none seem to apply that I have it inside an Angular Directive
index.html
<!DOCTYPE html>
<html>
<head>
<title>AngularJS + Highcarts </title>
<link href='http://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
<link href='css/highChartCss.css' rel='stylesheet' type='text/css'>
</head>
<body>
<select id="chartType">
<option value="0">-select chart type-</option>
<option value="line">line</option>
<option value="column">column</option>
</select>
<div id="content">
</div>
<div id="graph">
<section ng-app='charts'>
<div ng-controller="Ctrl">
<highchart chart='CDHLeads'></highchart>
</div>
</section>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="js/webSocket.js"></script>
<script type="text/javascript" src="js/highChartAngular.js"></script>
</body>
</html>
highChartAngular.js
function log() {
var formattedDate = new Date();
document.getElementById("content").innerHTML = formattedDate;
}
Highcharts.setOptions({
colors: ['#0266C8', '#0EE', '#F93', '#DDDF00', '#F90101']
});
function buildChart(title, yAxisLabel, xAxisLabels, series) {
$(function () {
$('#container').highcharts({
credits: {
enabled: false
},
chart: {
renderTo: 'CDHLeads',
type: 'column',
backgroundColor: '#000000'
},
legend: {
itemStyle: {
fontSize: '12px',
font: '12pt Inconsolata, sans-serif',
color: '#FFF'
}
},
title: {
text: title,
style: {
font: '12pt Inconsolata, sans-serif',
color: 'white'
}
},
xAxis: {
categories: xAxisLabels,
style: {
font: '12pt Inconsolata, sans-serif',
color: 'white'
}
},
plotOptions: {
series: {
colorByPoint: false
}
},
yAxis: {
title: {
text: yAxisLabel
},
tyle: {
font: '12pt Inconsolata, sans-serif',
color: 'white'
}
},
series: series
});
});
$("#chartType").change(function() {
var type = this.value;
if(type !== '0') {
var cdh = $('#CDHLeads').highcharts();
$(cdh.series).each(function(){
this.update({
type: type
}, false);
});
cdh.redraw();
}
});
}
var app = angular.module('charts', []);
app.directive('highchart', [function () {
return {
restrict: 'E',
template: '<div id="container">',
replace: true,
link: function (scope, element, attrs) {
scope.$watch(attrs.chart, function () {
if (!attrs.chart) return;
var chart = scope.$eval(attrs.chart);
angular.element(element).highcharts(chart);
});
}
}
}]);
function Ctrl($scope) {
$scope.example_chart = buildChart();
}
Instead
var cdh = $('#CDHLeads').highcharts();
use
var cdh = $('#container').highcharts();
because in your template , container is the chart id.
I suspect it's the following two lines that are the problem:
var cdh = $('#CDHLeads').highcharts();
$(cdh.series).each(function(){
What the error message is telling you is that cdh is undefined. I think it's because $('#CDHLeads') isn't actually finding the chart element you're after at you've not set the ID field. I'd try changing:
<highchart chart='CDHLeads'></highchart>
to
<highchart id="CDHLeads" chart='CDHLeads'></highchart>

Categories