I'm using chart.js to make, unsurprisingly, a chart, and I'm trying to figure out how to cleanly and correctly rewrite my code in angular.js.
我正在使用chart.js制作一个图表,不出所料,我正试图弄清楚如何在angular.js中干净利落地重写我的代码。
Vanilla Implementation
If I were just using vanilla javascript and html, I'd probably do something that boils down to this:
如果我只是使用vanilla javascript和html,我可能会做一些归结为这个:
<canvas id='chart'></canvas>
<script>
data = {...} // dictionary of chart data, omitted for brevity
options = {...} // dictionary of chart options, same^
var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx).Line(data, options);
</script>
And first the canvas would load, then the script would run and draw the chart.
首先画布将加载,然后脚本将运行并绘制图表。
Angular
But with angular, I can have, instead,
但有角度,我可以,相反,
<ng-chart></ng-chart>
<script>
angular.module('app')
.directive('ngChart', function(){
return {
restrict: 'E',
template: '<canvas></canvas>'
...
}
)
</script>
and put the same javascript from the first example inside the directive.
并从指令中的第一个示例中输入相同的javascript。
...
But where?
It seems like it should be in either a link function, or the controller. I need the DOM elements to load first, because otherwise drawing on the canvas won't work--but that doesn't seem to limit it. I also would like to be able to re-draw the graph, so that I can eventually add the ability to filter/rescale the graph without reloading the whole page.
它似乎应该在链接功能或控制器中。我需要首先加载DOM元素,因为否则在画布上绘制将不起作用 - 但这似乎并不限制它。我也希望能够重新绘制图形,这样我最终可以添加过滤/重新缩放图形的功能,而无需重新加载整个页面。
1 个解决方案
#1
1
under the link
property.
在链接属性下。
<script>
angular.module('app')
.directive('ngChart', function(){
return {
restrict: 'E',
link: function (scope, element, attrs, controllers) {
//your plugin implementation here
data = {...} // dictionary of chart data, omitted for brevity
options = {...} // dictionary of chart options, same^
var ctx = element.getContext("2d");
var chart = new Chart(ctx).Line(data, options);
}
template: '<canvas></canvas>'
}
)
</script>
#1
1
under the link
property.
在链接属性下。
<script>
angular.module('app')
.directive('ngChart', function(){
return {
restrict: 'E',
link: function (scope, element, attrs, controllers) {
//your plugin implementation here
data = {...} // dictionary of chart data, omitted for brevity
options = {...} // dictionary of chart options, same^
var ctx = element.getContext("2d");
var chart = new Chart(ctx).Line(data, options);
}
template: '<canvas></canvas>'
}
)
</script>