2013-09-23 75 views
2

我正在学习Javascript和AngularJS,通过集成两个示例:Spring MVC and AngularJSAngularJS and HighchartsAngularJS for Highcharts with dynamic ajax data

这个看似简单的任务使我感到困惑了几天: 在Spring REST驱动的后端中,我添加了Book的一个属性“prices”,一个双精度数组来表示每月或每年的价格书。该AngularJS客户端显示的“价格”,加入以下代码的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> 

和下面的代码到控制器:动态

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

表更新从后端数据。非常整洁优雅!

让我感到困惑的是highcharts部分。添加以下到HTML:

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

和一些静态值的“价格”到控制器:

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 
} 

而且hichcharts正常工作与AngularJS。

我然后试图通过添加一些代码到控制器以更新从后端到图表的动态“价格”:

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

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

和在一段时间后意识到这是对AngularJS的相当天真的理解。我也遵循

How to produce a highchart (using angular js) with json data coming from an Ajax request中描述的方式没有成功。

是否有像上面显示的价格表一样的优雅方式让Highcharts显示来自后端的动态数据?

+0

你不在加载数据后需要重新加载图表? –

+0

查看第一个示例[link](https://github.com/robharrop/spring-angularjs)。按下UI上的按钮(例如书籍详细信息)后,图表应该重新加载。 – Copacabana

回答

3

试着在你的星盘的配置直接更改数据:

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

或者使用对象为系列:后来

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 
} 

然后:刚刚

prices.data = [60.5, 55.7] 
+1

谢谢,你救了我@Pablojim的时间 – vinothini