Reputation: 5205
I am using in my node app chartJS 2.7.1
.
My pug file looks like the following:
extends layouts/_layout.pug
block content
.page-title
div
h1
i.fa.fa-dashboard
| Bitcoin Price Example
.row
.col-md-12
.card
h3.card-title Loading local bitcoin file
canvas#canvas.chartjs-render-monitor(style='display: block; width: 1000px; height: 500px;', width='1000', height='500')
console.log(data)
block specific-js
script(type='text/javascript', src="js/chartJS_price.js")
script(type='text/javascript', src="js/plugins/chart.js") // The Chart JS library
The chartJS_price.js
file looks like the following:
const lineChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "Price",
borderColor: 'rgba(255,99,132,1)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
fill: false,
data: [
5,
6
],
yAxisID: "y-axis-1",
}, {
label: "MarketCap",
borderColor: 'rgba(54, 162, 235, 0.2)',
backgroundColor: 'rgba(54, 162, 235, 1)',
fill: false,
data: [
1,
3
],
yAxisID: "y-axis-2"
}]
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = Chart.Line(ctx, {
data: lineChartData,
options: {
responsive: true,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Bitcoin Price and MarketCap'
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
}],
}
}
});
};
The route in my app.js
file looks like the following:
// routes
app.get('/price', (req, res) => {
const priceData = JSON.parse(fs.readFileSync(path.join(__dirname, './data/prices.json'), 'utf8'))
res.render('prices', {
priceData,
})
})
As you can see I am loading the price
data in the route
and pass it to the view
. I am loading the script in my pug
file with my custom chartjs
specifications.
Any suggestions how to inject my priceData
variable from my route into the in the pug-template loaded chartJS_price.js
.
Any suggestions how to do this?
Upvotes: 0
Views: 1932
Reputation: 1051
The pug file is fine, you only have to make some changes to your chart_price.js
file, make a request to the server via ajax, and in your server file, instead of rendering the file, read the file content and use
res.send(//your json data)
.
Upvotes: 1