I am facing an issue with displaying a chart or table in a div based on an XHR response. In the case of a chart, I want to replace the div contents with a canvas element that will be used by chart.js to show a graph.
When I directly include the canvas element in the HTML code, angular-chart.js successfully renders the graph. However, if I dynamically inject the canvas into the div using JavaScript, although the canvas element is present in the DOM, the chart does not display.
How can I resolve this problem?
HTML
<div ng-controller="ChartCtrl">
<div>
{{chart.name}}
This works (doughnut):
<canvas id="chart-{{$index}}" class="chart chart-doughnut" chart-data="chart.data" chart-labels="chart.labels"></canvas>
</div>
This Doesn't work ({{chart.type}}):
<div id="chartDiv"> </div>
</div>
Javascript
var myApp = angular.module('myApp', ['chart.js']);
// Create the controller, the 'ToddlerCtrl' parameter
// must match an ng-controller directive
myApp.controller('ChartCtrl', function ($scope) {
var chart_div = $('#chartDiv');
chart_div.empty();
canvas_html = '<canvas id="chart-2" class="chart chart-doughnut" chart-data="chart.data" chart-labels="chart.labels"></canvas>';
console.log(canvas_html)
chart_div.append(canvas_html);
//console.log(chart_div)
$scope.chart = {
name: 'Chart 1',
type: 'Doughnut',
labels: ['EVSC', 'ISB'],
data: [13, 44]
};
});
Plunker Example: http://plnkr.co/edit/9JkANojIl8EXRj3hJNVH?p=preview