我想将通过查询从数据库中检索到的编码 JSON 数据加载到 Angular-nvD3 图中,但我不知道该怎么做,也不知道哪种方式最适合完成此类任务。
我使用 API 从数据库(表 PRODUCTS)中检索带有查询的编码 JSON 数据。我已经通过对给定 api 的 $http
请求(加载到工厂中)成功地将此类数据加载到表中。数据作为对象保存到工厂中的字典中,并向 api(位于服务中)发出 $http
请求。
表格示例(表格PRODUCTS):
身份证
1 100
2275
工厂样本:
.factory('services', ['$http', function($http){
var serviceBase = 'services/'
var object = {};
object.getData = function(){
return $http.get(serviceBase + 'data');
};
return object;
}]);
将数据显示到表中的 Controller 示例( View 中带有“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
中?
非常感谢!
最佳答案
您所要做的就是在收到数据后映射数据。我 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
});
});
});
关于javascript - 将 JSON 数据加载到 Angular-nvD3 Graph (AngularJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36559287/