search

Home  >  Q&A  >  body text

angular.js - 如何将d3(js库)与angular同使用?

我想用angular封装一个指令,将d3.js画图的功能写进去。
首先我仿照网上的例子,将d3.js用factory包了起来,js文件命名为d3.js

然后我在 directive.js文件中把d3.js绘制柱状图封装:

之后在页面中引用了指令

最后再app.js中注入了依赖如图:

现在有些报错如下:

请教如何解决这个问题呢。哪里出了问题?angular新手,请大家在各方面指教。。

黄舟黄舟2745 days ago574

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-05-15 17:03:40

    Looking at the organizational structure of your code, it seems that module management is not used, so introduce d3 first and use it directly. There is no need to cover d3 in one layer, and it will not be convenient for future upgrades

    <script src="lib/d3.js"></script>
    <script src="lib/angular.js"></script>

    Use directly

    angular.module('myApp.directive', [])
            .constant('d3',d3)
            .directive('d3Bars', function (d3) {
                return {}
            });
    
    angular.module('myApp', ['myApp.directive'])
            .controller(function () {
    
            });

    If possible, it is recommended that you separate the drawing logic from your business and extract another module, such as

    angular.module('ngD3', [])
            .constant('d3',d3)
            .directive('d3Bars', function (d3) {
                return {}
            });

    Maybe you will contribute an awesome photo gallery in the future

    reply
    0
  • 黄舟

    黄舟2017-05-15 17:03:40

    If you want to use existing wheels, I recommend you take a look at angular-nvd3. There are also examples
    If you want to try it yourself, I recommend you take a look at Creating Charting Directives Using AngularJS and D3.js (you may need to bypass the wall...)

    reply
    0
  • Cancelreply