Search code examples
angularjssparklines

jQuery Sparkline bar chart not working on Angularjs ng-repeat


I am trying to use jquery.sparkline.js to show bar chart on my html table. But the moment I use ng-repeat my sparkline doesn't work.

<tr ng-repeat='x in [1]'>
    <td>{{x}}</td>
    <td>33</td>
    <td>
        <span class="dynamicbar">Loading..</span>
    </td>
</tr>

When you look at the ng-repeat its nothing but a dummy data, but after I use ng-repeat my sparkline doesn't render. The reason I want this option is I have a html table with different rows have different data so I need barchart in one of the table column.

Here is the plunker:

http://plnkr.co/edit/MQ0JFg75RvfKKFiATz84?p=preview

The plunker works if we remove ng-repeat and bar chart shows up

How can I make this work using ng-repeat and bind the bar chart?


Solution

  • You should never initialize jQuery plugins in Angular controllers simply because it's not guarantied that HTML element you are after is going to be present in the DOM (due to compilation and rendering). Instead create simple directive:

    app.directive('dynamicbar', function() {
      return {
        scope: {
          data: '='
        },
        link: function(scope, element) {
          element.sparkline(scope.data, {
            type: 'bar',
            barColor: 'green',
            width: 300,
            height: '50',
            barWidth: 8,
            barSpacing: 3,
            colorMap: ["green", "yellow", "red"],
            chartRangeMin: 0
          });
        }
      }
    })
    

    and use it in template:

    <tr ng-repeat='x in items'>
        <td>22</td>
        <td>33</td>
        <td>
            <span dynamicbar data="x.bars">Loading...</span>
        </td>
    </tr>
    

    Demo: http://plnkr.co/edit/6wO6zKcRYdtrN6Xmbj9E?p=preview