angular-nvd3 and Browserify

angular-nvd3 and Browserify

本文关键字:Browserify and angular-nvd3      更新时间:2023-10-06

如何让angular-nvd3与Browserify一起工作?我通过npm install angular-nvd3安装,然后使用以下内容创建我的模块。

require('angular').module('myApp', [require('angular-nvd3')]);

我的控制器看起来像

require('angular')
  .module('myApp')
  .controller('MyCtrl', function() {
    var ctrl = this;
    ctrl.nvd3Options = {
        chart: {
            type: 'discreteBarChart',
            height: 450,
            margin : {
                top: 20,
                right: 20,
                bottom: 60,
                left: 55
            },
            // ...other options from demo...
        }
    };
    ctrl.nvd3Data = [{
        key: "Cumulative Return",
        values: [
            { "label" : "A" , "value" : -29.765957771107 },
            // ...other data from demo...
        ]
    }];
  });

我的HTML看起来像

<div ng-app="myApp" ng-controller="MyCtrl as ctrl">
  <nvd3 options='ctrl.nvd3Options' data='ctrl.nvd3Data'></nvd3>
</div>

但我得到了错误ReferenceError: nv is not defined@angular-nvd3.js:250(使用v1.0.5)。

我认为安装和要求angular-nvd3可以处理所有的依赖关系(即nvd3和d3)。但这些依赖关系并没有得到处理。

当前解决方案

为了解决这个问题,我在HTML中显式地安装了d3、nvd3和<script>;(但这恰恰违背了目的。

我找到了一个更好的方法。添加

global.d3 = require('d3'); // nvd3 assumes that d3 is global
require('nvd3');

无论您在哪里定义模块,并确保将这些包添加到package.json依赖项中。

然后我就用通常的方式(在我的情况下是狼吞虎咽)。