How to use Angular-Charts JS? - javascript

Apart from the documentation I read (usually not helpful), I found some chart examples I want to implement to my page, but it seems not working. I tried to tweak it around but every time it gets load, it always displaying blank on the page.
Here's the code:
<div data-ng-controller="LineCtrl as line">
<canvas> data-sys-chart-line
data-dataset="line.data"
width="400"
height="240"></canvas>
</div>
<script type="text/javascript">
(function () {
'use strict';
function LineCtrl ( ) {
this.data = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [
{
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
data: [40, 10, 60, 70, 20, 20]
},
{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
data: [30, 70, 40, 90, 60, 70]
}
]
};
}
})();
</script>
<!-- Includes Dependencies here: AngularJS & Chart.js -->
<script src="script/Chart.js"></script>
<script src="script/angular-chart.min.js"></script>
<script src="script/tc-angular-chartjs.min.js"></script>
<script>
I included those .js files under /script folder in my project folder.

i have never used Chart.js before but seems that u are doing it wrong
you have never initialize the chart, by reading the documentation like for 10 second i found that you have to initialize it like this
var ctx = document.getElementById("here_is_the_canvas_element").getContext('2d');
var myChart = new Chart(ctx, { ... })
and you are using Chart.js code before you include the library

Related

How can I configure Chart.js in a Electron app?

I'm new to electron so I'm learning the basic configuration.
So, i want to implement chart.js in my electron app.
The problem is: on my main page, the chart is simply a blank space... but with a look in the html inspector I can see the canvas created.
What I already did:
I've installed chart.js with npm install chart.js --save which we can find in the official chart.js documentation (https://www.chartjs.org/docs/latest/getting-started/installation.html).
My feeling tells me that I'm doing something wrong in the call for the chart library or something like that. My code is below:
<canvas id="myChart"></canvas>
<script>
const { chart } = require('electron-chartjs');
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
</script>
As you can see, I'm using the official example. The only addition was the const { chart } = require('electron-chartjs');. So, I believe I'm doing something wrong or ignoring some big step.
Update:
Here is the new code:
<canvas id="chart"></canvas>
<script>
var Chart = require('chart.js');
var ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45]
}]
},
// Configuration options go here
options: {}
});
</script>
I had to require "chart.js", but i was requiring "electron-chart,js". And the canvas id was wrong.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
// ** entire Chart.js library **
</script>
<style>
</style>
</head>
<body>
<canvas id="myChart"></canvas>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: {{chartData}}
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
</script>
</body>
</html>
Notice the placeholder {{chartData}}. Also do note that you have to substitute in the actual script from the Chart.js file (you could link to the script file, but then you'll need a module that serves up static files)
var http = require('http');
var fs = require('fs');
http.createServer(function (req, response) {
fs.readFile('index.html', 'utf-8', function (err, data) {
response.writeHead(200, { 'Content-Type': 'text/html' });
var chartData = [];
for (var i = 0; i < 7; i++)
chartData.push(Math.random() * 50);
var result = data.replace('{{chartData}}', JSON.stringify(chartData));
response.write(result);
response.end();
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
We just substitute the placeholder with actual data.
Update for electron 21.2.0.
Download chart.js module from npm
Modify Index.html:
Add 'unsafe-inline' in meta
<meta http-equiv="Content-Security-Policy" content="default-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'">
Now we can use chart.js as usual.
I only have no idea how to set custom width/height of my chart ):
Demo code is available on:
https://github.com/zdzmzych/electronNoiseAnalyzer

Pug - Access data from server in pug script(type='text/javascript')

I am trying to load data from the server in my pug template.
My route looks like the following:
app.get('/serverdata', async(req, res) => {
const chartData = []
for (const i = 0; i < 7; i++) {
chartData.push(Math.random() * 50)
}
const result = JSON.stringify(chartData)
res.render('serverdata', {
result,
})
})
My pug template looks like the following:
.row
.col-md-12
.card
.embed-responsive.embed-responsive-16by9
canvas#myNewChart(style='display: block; width: 1000px; height: 500px;', width='1000', height='500')
block specific-js
script(type='text/javascript', src="js/plugins/chart.js")
script(type='text/javascript').
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: result //here I am getting the error
}
]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
My error is within my view file:
serverdata:13 Uncaught ReferenceError: result is not defined
at serverdata:13
Any suggestions how to load server data in the script. tag of my pug file?
I appreciate your replies!
I think you are mixing different contexts. The line that gives you an error is executed in the browser, and in that context, there is no variable named result.
Since you have a endpoint /serverdata on your server in place, all you need to load and parse the data from that URL. Details depend on what kinds of JavaScript libraries you are using, but with jQuery getJSON:
$.getJSON("/serverdata", function(data) {
/* Update your chart by using 'data' */
});

I don't want to auto reflect chart with $watch in angulars js?

Right now I am implementing line chart in angular js. And I have written one directive for this, So it is working fine, But when I am putted $watch in this directive then every time chart will updating continuously. I want to use $watch for some dynamic change after loaded the page.
angular.module('app.abc').directive('linechart', function () {
return {
restrict: 'A',
template:'',
link: function (scope, element, attributes) {
scope.$watch(function(){
var lineOptions = {
scaleShowGridLines : true,
scaleGridLineColor : "rgba(0,0,0,.05)",
scaleGridLineWidth : 1,
bezierCurve : true,
};
var lineData = { labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var ctx = element[0].getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
})
}
}
});
<canvas style="display: block;" linechart height="120" ></canvas>
Line chart reflecting updates is contiguously. But I don't want to reflection continuously. I have tried to put my ctx object outside of $watch, but chart is not showing anything. Actually I am new in angular js and also new in directives. Please give me idea how handle this directive with $watch. I have seen one demo(based on javascript) example https://codepen.io/SitePoint/pen/mJRrKw

Property Line from NuGet-package Chart.js 2.0.2 not available

I want to use charts in my HTML-pages, which i make in a web project made with VS 2015.
So i installed the NuGet-package Chart.js:
Description for installation of Chart.js
After the installation i see two new JS-scripts in the scripts-folder:
Charts.js and Charts.min.js
Next i tried to implement a line diagram/chart in my page.
<!DOCTYPE html>
<html>
<head>
<title>Display charts with Chart.js</title>
<script type="text/javascript" src="../scripts/Chart.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<form>
<h3>Example for display of chart data</h3>
<canvas id="buyers" height="600" width="400"></canvas>
<script type="text/javascript">
var buyerData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [
{
fillColor: "rgba(172,194,132,0.4)",
strokeColor: "#ACC26D",
pointColor: "#fff",
pointStrokeColor: "#9DB86D",
data: [203, 156, 99, 251, 305, 247]
}
]
}
var buyers = document.getElementById("buyers").getContext("2d");
new Chart(buyers).Line(buyerData);
</script>
</form>
</body>
</html>
But each time i try to start the page, i get a message, that the property Line does not exist.
What's wrong?
Thanks in advance!
I have found a solution, but i'm not absolutely sure about it.
If want to post other answers, You are invited.
I replaced the line
new Chart(buyers).Line(buyerData);
by
var myChart = new Chart(buyers, { type: 'line', data: buyerData });
Further i discovered another option:
var myChart = Chart.Line(buyers, { data: buyerData });

Chartjs v2 xAxes label overlap with scaleLabel

The chart js v2 is overlapping with is there a way to move the labelString of scaleLabel further down so that it does not overlap.Please view the screen shot marked in yellow and red part.
Part of the code is as following
scales: {
xAxes: [{
display: true,
ticks: {
autoSkip: false,
autoSkipPadding: 20
},
scaleLabel: {
display: true,
labelString: "ProductName(ProductName)"
}
}],
There are two possible solutions to your problem:
1: This is for a line chart, but can easily tailored to a bar chart.
The legend is part of the default options of the ChartJs library. So
you do not need to explicitly add it as an option.
The library generates the HTML. It is merely a matter of adding that
to the your page. For example, add it to the innerHTML of a given DIV.
(Edit the default options if you are editing the colors, etc)
<div>
<canvas id="chartDiv" height="400" width="600"></canvas>
<div id="legendDiv"></div>
</div>
<script>
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "The Flash's Speed",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Superman's Speed",
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myLineChart = new Chart(document.getElementById("chartDiv").getContext("2d")).Line(data);
document.getElementById("legendDiv").innerHTML = myLineChart.generateLegend();
</script>
2: Adding a legend template in chart options
You'll also need to add some basic css to get it looking ok.
//legendTemplate takes a template as a string, you can populate the template with values from your dataset
var options = {
legendTemplate : '<ul>'
+'<% for (var i=0; i<datasets.length; i++) { %>'
+'<li>'
+'<span style=\"background-color:<%=datasets[i].lineColor%>\"></span>'
+'<% if (datasets[i].label) { %><%= datasets[i].label %><% } %>'
+'</li>'
+'<% } %>'
+'</ul>'
}
//don't forget to pass options in when creating new Chart
var lineChart = new Chart(element).Line(data, options);
//then you just need to generate the legend
var legend = lineChart.generateLegend();
//and append it to your page somewhere
$('#chart').append(legend);
Either of these two options will work.
In your case the legend code will look something like this
(Assuming you already have a BarChart Generated)
<div id="legendDiv"></div>
document.getElementById("legendDiv").innerHTML = BarChart.generateLegend();
Then use css to format the legend however you would prefer (including adding spacing between the legend in the chart)

Categories