How to produce a highchart (using angular js) with json data coming from an Ajax request

前端 未结 1 465
北海茫月
北海茫月 2021-01-03 04:24

My question is related to the link How to handle Highcharts events from an AngularJS directive?. What if I want to have the highchart generated from dynamic data? my chart

相关标签:
1条回答
  • 2021-01-03 05:15

    Solution to the Problem:-

    I solved the problem by myself. I am posting this solution for my future reference and in case it helps somebody having the same requirement.

    The javascript was modified so that the Name and Score could be accessed from the json data. They were stored in the 'name' and 'score' arrays which were passed to the chart option object in order to render the highchart.

    var app = angular.module('charts', []);
    
    app.directive('highchart', function () {
    return {
        restrict: 'E',
        template: '<div></div>',
        replace: true,
    
        link: function (scope, element, attrs) {
    
            scope.$watch(function () { return attrs.chart; }, function () {
    
                if (!attrs.chart) return;
    
                var charts = JSON.parse(attrs.chart);
    
                $(element[0]).highcharts(charts);
    
            });
        }
    };
    });
    
    
    app.controller('Ctrl', function ($scope, $http, $timeout) {
    $http.get('http://localhost:1234/abc/pqr').success(function (data, status) {
    
        var score = [];
        for (var i = 0; i < data.length; i++) {
            score.push(data[i].Score);   
        }
    
        var name = [];
        for (var i = 0; i < data.length; i++) {
            name.push(data[i].Name);
        }
    
        $scope.renderChart = {
            chart: {
                type: 'bar'
            },
            xAxis: {
                categories: name
            },
            series: [{
                data: score
            }],
            legend: {
                enabled: false
            }
        };
    }).error("error message");
    $timeout($scope.fetch, 1000);
    });
    
    0 讨论(0)
提交回复
热议问题