i am trying some time now, to get the Chart.js in external file working with Thymeleaf. I was checking in countless external forums but couldnt find an answer. The closes to what i could find is the following Thymeleaf external javascript file shares the module attributes with html file
but i still didn't manage to do it.
Here is my Controller
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ChartController {
@RequestMapping("/ExternalChart")
public String hello(Model model) {
String label[] = {"a","b","c","d","e","f","g","adasda","adasda2"};
int point[] = {5,3,7,1,8,3,4,50};
model.addAttribute("label",label);
model.addAttribute("point",point);
return "ExternalChart";
}
}
html file is located in src/main/resources/templates/
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link href="../static/css/Layout.css" th:href="@{/css/test.css}"
rel="stylesheet" />
<link href="../static/js/drawChart.js" th:href="@{/js/drawChart.js}"
rel="javascript" />
</head>
<body>
<h2>Donkey</h2>
<p>punch</p>
<canvas id="ChartDemo"></canvas>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<script type="text/javascript" th:inline="javascript"
th:src="@{/js/drawChart.js}">
/*<![CDATA[*/
var xAxisData = /*[[ ${label} ]]*/[];
var yAxisData = /*[[ ${point} ]]*/[];
drawchart(xAxisData, yAxisData);
/*]]>*/
</script>
</body>
</html>
My javascript. it is located in src/main/resources/static/js
function drawchart(xAxisData, yAxisData) {
var ctx = document.getElementById("ChartDemo").getContext('2d');
var ChartDemo = new Chart(ctx, {
type : 'line',
data : {
labels : xAxisData,
datasets : [ {
label : "Chart-1",
borderColor : 'rgb(255, 0, 0)',
lineTension : 0,
fill : false,
data : yAxisData,
}, ]
},
options : {
responsive : true,
}
});
}
What i have noticed is that the attributes xAxisData and yAxisData get the values, but it seams that the drawChart(xAxisData,yAxisData) doesn't not get executed in browser.
I assume that i am making some silly mistake, and prospects of me finding it alone is close to zero. Thanks to anybody even trying to help me out BR HK
p.s. i am really new with JS