Search code examples
angularjschartsangularjs-directivec3.jsc3

custom attribute type directive to set the background color of c3 chart


I am using Wasil C3 angularjs directives (http://wasil.org/angularjs-directive-for-c3-js-tutorial) and there is also a sample plunker through compilation (http://plnkr.co/edit/wiiUMk2KoHHrK4D1HdNu?p=preview). As need to set the back ground color of the sub chart, I am trying to create a custom attribute directive (subChartBgColor), so that on which ever chart I want to set back ground color of the sub chart I can simple put the attribute sub-chart-bg-color on Html tag, but some how it is not working. Can any one help me to fix my subChartBgColor directive :

 (function() {
         angularDemo.directive('subChartBgColor', [function() {
             return {
                 restrict: 'A',
                 scope: false,
                 link: function(scope, element, attrs) {
                     d3.selectAll("svg > g:nth-child(3)").insert("rect", ":first-child").attr("width", "100%").attr("height", "100%").attr("fill", "yellow");
                 }
             }

         }]);

Solution

  • Firstly, I'm not familiar with angular. Basically, after the chart is created, you insert the rectangle, and then style the background colour of the rectangle.

    Since I don't know angular very well, and I don't know how the timing of events / binding works, I have used setTimeout to wait for the chart to be created, before inserting the rectangle. You will need to move this code into the appropriate directive.

    It's the exact same code as the other answer:

    setTimeout(function(){
        d3.selectAll("svg > g:nth-child(3)").insert("rect", ":first-child").attr("width", "100%").attr("height", "100%").attr("fill", "yellow");
    }, 1000);
    

    See: http://plnkr.co/edit/CBcIsW9QnHaeXicmwZk2?p=preview