AngularJS for Highcharts with dynamic ajax data

安稳与你 提交于 2019-12-05 02:16:52

问题


I'm learning Javascript and AngularJS by integrating two examples: Spring MVC and AngularJS and AngularJS and Highcharts.

This seemingly simple task has puzzled me for a few days: In the Spring REST-powered backend, I added the class Book with a property "prices", an array of doubles to represent the monthly or yearly prices of the book. The AngularJS client shows the "prices" by adding the following code to html:

<div style="height:300px;width:250px;overflow:auto;float:left;">
    <table class="table table-striped">
       <tr ng-repeat="price in book.prices">
          <td>{{price}}</td>
       </tr>
    </table>
</div>

and the following code to the controller:

 var bookId = $routeParams.bookId;
 if (bookId === 'new') {
    $scope.book = new Book();
 } else {
    $scope.book = Book.get({bookId: bookId});
 }

The table updates dynamically with the data from the backend. Pretty neat and elegant!

What baffles me is the highcharts part. I added the following to the html:

<div style="border: 1px solid #ccc; width: 620px; float: right">
     <highchart id="chart1" config="chartConfig"></highchart>
</div>

and some static values for the "prices" to the controller:

var prices = [60.5, 55.7]; // Static data works

$scope.chartConfig = {
    options : {
        chart : {
            type : 'line'
        }
    },
    series : [ {
        data : prices 
    } ],
    title : {
        text : 'Monthly Book Prices'
    },

    loading : false
}

And the hichcharts works fine with AngularJS.

I then tried to update the dynamic "prices" from the backend to the chart by adding some code to the controller:

// var prices = [60.5, 55.7]; // Static data works
var prices = $scope.book.prices

or

// var prices = [60.5, 55.7]; // Static data works
var prices  = [$scope.book.prices]

and after some time realized this was a quite naive understanding of AngularJS. I've also followed the way described in

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

Is there an elegant way like the prices table shown above for the Highcharts to display the dynamic data from backend?


回答1:


Try changing the data in your chart config directly:

$scope.chartConfig.series[0].data = $scope.book.prices 

Or use an object for the series:

var prices = {data: [60.5, 55.7]}; // Static data works

$scope.chartConfig = {
    options : {
        chart : {
            type : 'line'
        }
    },
    series : [ prices ],
    title : {
        text : 'Monthly Book Prices'
    },

    loading : false
}

Then later:

prices.data = [60.5, 55.7]


来源:https://stackoverflow.com/questions/18961523/angularjs-for-highcharts-with-dynamic-ajax-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!