将 JSON 数据加载到 Angular-nvD3 图表中(AngularJS)

Load JSON Data into Angular-nvD3 Graph (AngularJS)

我想将通过查询从数据库中检索到的编码 JSON 数据加载到 Angular-nvD3 图中,但我不知道该怎么做,也不知道哪种方式最好这样的任务。

我使用 api 从数据库(table PRODUCTS)检索带有查询的编码 JSON 数据。我已经通过 $http 请求(加载到工厂)成功地将此类数据加载到 tables 到给定的 api。数据作为对象保存到工厂中的字典中,并向 api(位于服务中)发出 $http 请求。

table(table 产品)示例:

ID 库存

1 100

2 275

工厂样品:

.factory('services', ['$http', function($http){
  var serviceBase = 'services/'
  var object = {};
  object.getData = function(){
    return $http.get(serviceBase + 'data');
  };
  return object;
}]);

将数据显示到 table 中的控制器示例(视图中带有“ng-repeat="data in get_data"”):

.controller('TablesCtrl', ['$scope', 'services', function($scope, services) {

  services.getData().then(function(data){
    $scope.get_data = data.data;
  });

}]);

数据格式示例:

[{"0":"1","1":"100","ID":"1","STOCK":"100"},{"0":"2","1":"275","ID":"2","STOCK":"275"}]

饼图 - 这是我要添加的脚本类型的示例(来自 THIS 存储库):

'use strict';

angular.module('mainApp.controllers')

.controller('pieChartCtrl', function($scope){

    $scope.options = {
        chart: {
            type: 'pieChart',
            height: 500,
            x: function(d){return d.key;},
            y: function(d){return d.y;},
            showLabels: true,
            duration: 500,
            labelThreshold: 0.01,
            labelSunbeamLayout: true,
            legend: {
                margin: {
                    top: 5,
                    right: 35,
                    bottom: 5,
                    left: 0
                }
            }
        }
    };

    $scope.data = [
        {
            key: "One",
            y: 5
        },
        {
            key: "Two",
            y: 2
        },
        {
            key: "Three",
            y: 9
        },
        {
            key: "Four",
            y: 7
        },
        {
            key: "Five",
            y: 4
        },
        {
            key: "Six",
            y: 3
        },
        {
            key: "Seven",
            y: .5
        }
    ];
});

HTML:

<div ng-app="myApp">
    <div ng-controller="pieChartCtrl">
        <nvd3 options="options" data="data"></nvd3>
    </div>
</div>

我的问题是:如何将这种检索到的编码 JSON 数据加载到 Angular-nvD3 图形中,而不是将数据手动输入到 $scope.data 中?

非常感谢!

我想你想要d3.json()

https://github.com/mbostock/d3/wiki/Requests

此命令应加载任何 JSON 文件。由于您使用的是 NVD3,因此您的项目中应该已经有 D3。

您所要做的就是在收到数据后将其映射。我 updated the plunker 从我的评论中向您展示如何使用 lodash 执行此操作。

services.getData().then(function successCb(data) {
  $scope.data = _.map(data.data, function(prod) {
    return {
      key: prod.ID,
      y: prod.STOCK
    };
  });
});

或者,如果您不想使用 lodash(尽管它通常默认包含在 angular 应用程序中),您可以执行以下操作:

$scope.data = [];
services.getData().then(function successCb(data) {
  angular.forEach(data.data, function(prod) {
    $scope.data.push({
      key: prod.ID,
      y: prod.STOCK
    });
  });
});