Search code examples
javascriptjqueryangularjshighchartshighcharts-ng

How to add a new Highchart dynamically using Highchartsng


So what I'm trying to do is when a user clicks a button I want to add a new highchart element to the page. Currently I see that my container for the chart shows up but the chart does not.

Here is what I'm trying to do:

//This config works when I statically load a graph
$scope.someConfig ={ options: {chart:{type:'pie'}}, title :{text: 'Test'}, series:[{data: [1,2,3,4]}]} 

angular.element($('myElement')).append{
"<div class='myContainerClass'>"+
  "<highchart config='config' style='height: 100%; width: 100%'>"+"<\highchart>"+
"</div>"
);

I'm still pretty new at this so I'm wondering what is I'm doing wrong

Any advice would be awesome!

Thank you~


Solution

  • You need to compile that DOM using $compile API before appending it to the desired element. $compile service will make the binding working on that DOM with the scope specified in the brackets like ($scope).

    Code

    var compiledDOM = $compile("<div class='myContainerClass'>"+
      "<highchart config='config' style='height: 100%; width: 100%'>"+"<\highchart>"+
    "</div>")($scope)
    angular.element($('myElement')).append(compiledDOM)
    

    Rather than appending DOM you could also think of ng-repeat directive which will dynamically renders the DOM based on the array provided to it. Basically it renders that html until that array length is reached.

    So here in your case you could fill charts object which is basically an array. When users add new chart push one object to charts object which will config part like charts.push({config: configObject})

    <div ng-repeat="chart in charts" class='myContainerClass'>"+
          <highchart config='chart.config' style='height: 100%; width: 100%'><\highchart>
    </div>
    

    Toggle flag showHighChart to showing & hiding highcharts DOM.