作者:昂-恩意_180 | 来源:互联网 | 2023-08-18 07:11
IamnewtoAngularandFlot,butamexperiencedwithJqueryandJavascript.Iamabitconfusedabo
I am new to Angular and Flot, but am experienced with Jquery and Javascript. I am a bit confused about how to go about binding a Flot chart to Angular data models, since Flot is a JQuery plugin. I've searched around, but haven't been able to find an example.
我对角度和Flot都不熟悉,但是我有Jquery和Javascript经验。我对如何将Flot图表绑定到角度数据模型有点困惑,因为Flot是JQuery插件。我找遍了,但找不到一个例子。
I would also be happy to use highcharts, google-charts, or any other charting solution.
我也很乐意使用highcharts、google-charts或任何其他的图表解决方案。
2 个解决方案
67
Since charting involves heavy DOM manipulation, directives are the way to go.
由于图表涉及大量DOM操作,因此需要使用指令。
Data can be kept in the Controller
数据可以保存在控制器中
App.controller('Ctrl', function($scope) {
$scope.data = [[[0, 1], [1, 5], [2, 2]]];
});
And you can create a custom HTML tag1 specifying the model you want to get data from
您还可以创建一个自定义的HTML tag1,指定您希望从该模型获取数据
which angular can compile through a directive
哪个角可以通过指令进行编译?
App.directive('chart', function() {
return {
restrict: 'E',
link: function(scope, elem, attrs) {
var data = scope[attrs.ngModel];
$.plot(elem, data, {});
elem.show();
}
};
});
Example here.
例子。
This process is similar for most plugins that modify the DOM.
这个过程与大多数修改DOM的插件相似。
-*-
- * -
Also, you can watch for changes in the chart's underlying data and redraw it, so this way you can grab data through the $http service from your controller and update the view automatically. This can be achieved by modifying the linking function in the directive definition object
此外,您还可以监视图表底层数据的更改并重新绘制它,这样就可以通过控制器的$http服务获取数据并自动更新视图。这可以通过修改指令定义对象中的链接函数来实现
var chart = null,
opts = { };
scope.$watch(attrs.ngModel, function(v){
if(!chart){
chart = $.plot(elem, v , opts);
elem.show();
}else{
chart.setData(v);
chart.setupGrid();
chart.draw();
}
});
Notice the usage of Flot's API within the directive to achieve what we want.
注意在指令中使用Flot的API来实现我们想要的。
Here the full example
这里完整的例子
1 Can be an attribute too.
1也可以是一个属性。