amCharts-Angular动态更新图表数据

时间:2017-10-14 16:19:09

标签: javascript angularjs amcharts

使用amCharts-Angular指令:https://github.com/GrantMStevens/amCharts-Angular

我有一个函数从promise中加载初始chartOptions对象,该函数在页面加载时成功呈现图表。但是,当我使用指令中包含的$scope.$broadcast('amCharts.updateData',options,'id')事件动态加载新选项时,图表将变为空白。

amChartsFactory.js



app.factory('amChartsFactory', ['$http', '$q', function($http, $q) {

  var service = {}

  service.chartOptions = {}

  service.getChartOptions = function(symbol) {
    var deferred = $q.defer()
    var querySymbol = symbol
    console.log(querySymbol, 'querySymbol')
    $http.get('/portfolio/get-chart-data?symbol=' + querySymbol)
      .then(function(response) {
  
        var chartOptions = {
          data: response.data.chart_data,
          type: "serial",
          categoryField: "timestamp",
          rotate: false,
          legend: {
            enabled: true,
            useGraphSettings: true
          },
          chartScrollbar: {
            enabled: true,
          },
          categoryAxis: {
            gridPosition: "start",
            parseDates: false
          },
          synchronizeGrid: true,
          valueAxes: response.data.axes_data,
          graphs: response.data.graph_data
        }

        service.chartOptions = chartOptions
        deferred.resolve(chartOptions)
      })
    return deferred.promise
  }

  return service

}])




当控制器加载以加载初始图表数据时,我调用函数amChartsFactory.getChartOptions('BTC'),这可以正常工作,并且图表会呈现。

但是,当我尝试动态更新数据时,例如vm.getChartData('ETH'),图表变为空白



app.controller('PortfolioController', PortfolioController)
PortfolioController.$inject = ['$scope', '$interval', '$timeout', '$http', 'portfolioFactory', 'amChartsFactory']

function PortfolioController($scope, $interval, $timeout, $http, portfolioFactory, amChartsFactory) {

  var vm = this

  vm.amChartOptions = amChartsFactory.getChartOptions('BTC') //this loads the initial chart

  vm.getChartData = function(symbol) { //this is supposed to use the same function to load new data, but the chart just goers blank
    amChartsFactory.getChartOptions(symbol)
      .then((options) => $scope.$broadcast('amCharts.updateData', options, 'currencyChart'))
  }

}




home.html的



<div class="chart-container" style="height: 600px;">
  <am-chart id="currencyChart" options="vm.amChartOptions" height="100%" width="100%"></am-chart>
</div>
&#13;
&#13;
&#13;

如何使图表动态呈现新数据?谢谢

1 个答案:

答案 0 :(得分:0)

amCharts.updateData事件用于更新图表的数据而不是选项/设置。

如果您真的想动态更改选项,则需要使用图表实例并访问它的属性或调用它的方法(有关完整参考,请参阅https://docs.amcharts.com/3/javascriptcharts/AmChart)。然后致电chart.validateNow()