Intergate flot with Angular js ——Angular 图形报表
下面这篇文章最终的结论就是 Flot 插件 结合 Angular 的Directive 来处理 图表的绘制
给出github上的一个demo源码。https://gist.github.com/flyysr/ba3a51cdbfcae7f53dec
最近项目中遇到了要显示图形报表的问题,项目的前端架构主要是基于 AngularJs 的,故,找js插件来显示图表(chart).
找到了Flot (http://www.flotcharts.org/), 说明一下,Flot是一个绘制图表的Js库。
下面问题的关键是怎么将 Flot和 Angular 整合起来。
----------------------------------------------------
显然,绘制图表涉及到大量的 DOM操作,而Angular的 Directive是有关html自定义标签的,所以这里的整合主要的用到 Angular的Directive的知识。
下面是我在StackOverflow上搜到的类似的提问:
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.
I would also be happy to use highcharts, google-charts(这几个也是js绘制图表的插件), or any other charting solution.
下面的是 stackOverflow上的最佳答案,这里记录之。
1、Since charting involves heavy DOM manipulation, directives are the way to go.
2、Data can be kept in the controller
1 2 3 | App.controller( 'Ctrl' , function ($scope) { $scope.data = [[[0, 1], [1, 5], [2, 2]]]; }); |
And you create custom html tag (Can be an attribute too) specifying the model you want to get data from.
1 | < chart ng-model='data'></ chart > |
which angular can compile through a directive.
1 2 3 4 5 6 7 8 9 10 | App.directive( 'chart' , function () { return { restrict: 'E' , link: function (scope, elem, attrs) { var data = scope[attrs.ngModel]; $.plot(elem, data, {}); elem.show(); } }; }); |
This process is similar for most plugins that modify the 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
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 achive what we want .
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现