【问题标题】:How to fetch json array data into highcharts in angularjs如何将json数组数据获取到angularjs中的highcharts
【发布时间】:2017-01-31 19:31:26
【问题描述】:

我想使用 highcharts 显示条形图。我在 play 框架 (play-java) 中开发一个应用程序,在其中我从 java api 返回一个响应,其中包含 json 格式的数据。它包含一个字段“名称” ' 其中包含“数据”、“小工具”、“其他”等数据。我希望图表的 x 轴从响应返回的 json 数组中获取这些值。

这是 .js 中响应的代码

for(var i=0;i<response.data.result.length;i++)
        {
            $scope.total=$scope.total+parseInt(response.data.result[i].item_price);
        }
        var j=0;
    console.log(response.data.result);
            while(j<response.data.result.length)
            {
                $scope.jsonArray=[{
                    name:response.data.result[j].category_name,
                    y: (parseInt(response.data.result[j].item_price)/$scope.total)*100,

                }]
                $scope.renderChart();
            }

条形图代码

$scope.renderChart = function()
{
    Highcharts.chart('container', {
        chart: {
            type: 'column'
        },
        title: {
            text: 'Your Expenses'
        },
        subtitle: {
            text: 'Your total spent money is '+$scope.total+'.'
        },
        xAxis: {
            type: 'category'
        },
        yAxis: {
            title: {
                text: 'Money spent in percentage'
            }

        },
        legend: {
            enabled: false
        },
        credits: {
            enabled: false
            },
        plotOptions: {
            series: {
                borderWidth: 0,
                dataLabels: {
                    enabled: true,
                    format: '{point.y:.1f}%'
                }
            }
        },

        tooltip: {
            headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
            pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
        },

        series: [{
            name: 'Categories',
            colorByPoint: true,
            data:$scope.jsonArray
         }]
    });
}

我知道我不能在提到的响应代码中使用 while 循环。这就是我正在寻找帮助的地方。y 轴应该计算百分比值。我想为 x 轴生成“名称”,为图表的 y 轴。在此先感谢..

【问题讨论】:

  • jsonArray 的控制台日志里有什么,根据 highcharts api 检查这个数组的格式是否正确

标签: javascript angularjs highcharts


【解决方案1】:

我们所要做的就是在循环之前将 jsonArray 初始化为空。添加一个 for 循环,以便它遍历数组并适当地分配值。 修改后的代码

$scope.jsonArray = [];
            for(var i=0;i<response.data.result.length;i++)
            {
                $scope.jsonArray[i]={
                    name:response.data.result[i].category_name,
                    y: (parseInt(response.data.result[i].item_price)/$scope.total)*100,

                }
                $scope.renderChart();
                console.log(response.data.result[i]);
            }

    console.log($scope.jsonArray);
    })

还是谢谢....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多