问题
I want to load encoded JSON Data retrieved with queries from a database into an Angular-nvD3 graph but I don't know how to do it or which way is the best to accomplish such task.
I retrieve encoded JSON data with queries from a database (table PRODUCTS) with an api. I have already successfully loaded such data into tables with $http
requests (loaded into a factory) to the given api. The data is saved as an object into a dictionary in a factory with $http
requests to the api (located in services).
Sample of the table (table PRODUCTS):
ID STOCK
1 100
2 275
Sample of the factory:
.factory('services', ['$http', function($http){
var serviceBase = 'services/'
var object = {};
object.getData = function(){
return $http.get(serviceBase + 'data');
};
return object;
}]);
Sample of a controller to display the data into a table (with "ng-repeat="data in get_data"
" in the view):
.controller('TablesCtrl', ['$scope', 'services', function($scope, services) {
services.getData().then(function(data){
$scope.get_data = data.data;
});
}]);
Sample of the data format:
[{"0":"1","1":"100","ID":"1","STOCK":"100"},{"0":"2","1":"275","ID":"2","STOCK":"275"}]
PIE CHART - This is an example of the type of script I want to addapt (from THIS repository):
'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>
My question is: how it is possible to load such retrieved encoded JSON data into an Angular-nvD3 graph instead of typing manually the data into $scope.data
?
Thank you very much!
回答1:
All you have to do is map your data once you receive it. I updated the plunker from my comment to show you how you might do this using lodash.
services.getData().then(function successCb(data) {
$scope.data = _.map(data.data, function(prod) {
return {
key: prod.ID,
y: prod.STOCK
};
});
});
Alternatively, if you don't want to use lodash (though it's usually included in angular applications by default), you could do something like:
$scope.data = [];
services.getData().then(function successCb(data) {
angular.forEach(data.data, function(prod) {
$scope.data.push({
key: prod.ID,
y: prod.STOCK
});
});
});
回答2:
I think you want d3.json()
https://github.com/mbostock/d3/wiki/Requests
This command should load any JSON file. Since you're using NVD3, you should already have D3 in your project.
来源:https://stackoverflow.com/questions/36559287/load-json-data-into-angular-nvd3-graph-angularjs