简体   繁体   中英

AngularJS: Directive with D3 chart in link function working only once

I've created an AngularJS directive which contains a D3 chart, like below:

 angular.module('main', [''])

    .directive('barChart', function() {

        return {

            restrict: 'E',
            replace: true,
            scope: {
            },
            template: '<svg class="chart" width="250" height="100"></svg>',
            link: function (scope, element, attrs, fn) {

            var d3 = window.d3;

             var data = {
             labels: [
               'LY', 'TY'
             ],
             series: [{
               label: 'LY',
               values: [2.8]
             }, {
               label: 'TY',
               values: [3.2]
             }]
           };


        var chartWidth = 150,
            barHeight = 30,
            groupHeight = barHeight,
            gapBetweenGroups = -10,
            spaceForLabels = 50,
            spaceForLegend = 50;

        // Zip the series data together (first values, second values, etc.)
        var zippedData = [];
        for (var i = 0; i < data.labels.length; i++) {
            for (var j = 0; j < data.series.length; j++) {
                zippedData.push(data.series[i].values[j]);
            }
        }

        // Color scale
        var color = d3.scale.category20();
        var chartHeight = barHeight * zippedData.length + gapBetweenGroups * data.labels.length;

        var x, y, yAxis, chart, bar;

        function setChartParameters() {
            x = d3.scale.linear()
                .domain([0, d3.max(zippedData)])
                .range([0, chartWidth]);

            y = d3.scale.linear()
                .range([chartHeight + gapBetweenGroups, 0]);

            yAxis = d3.svg.axis()
                .scale(y)
                .tickFormat('')
                .tickSize(0)
                .orient("left");

            // Specify the chart area and dimensions
            chart = d3.select(".chart")
                .attr("width", spaceForLabels + chartWidth + spaceForLegend)
                .attr("height", chartHeight);

            // Create bars
            bar = chart.selectAll("g")
                .data(zippedData)
                .enter().append("g")
                .attr("transform", function (d, i) {
                    return "translate(" + spaceForLabels + "," + (i * barHeight + gapBetweenGroups * (0.5 + Math.floor(i / data.series.length))) + ")";
                });
        }

        function drawBarChart() {

            setChartParameters();

            // Create rectangles of the correct width
            bar.append("rect")
                .attr("fill", function (d, i) {
                    return color(i);
                })
                .attr("class", "bar")
                .attr("width", x)
                .attr("height", barHeight - 1);

            // Add text label in bar
            bar.append("text")
                .attr("x", function (d) {
                    return x(d) - (-30);
                })
                .attr("y", barHeight / 2)
                .attr("fill", "red")
                .attr("dy", ".35em")
                .text(function (d) {
                    return d;
                });

            // Draw labels
            bar.append("text")
                .attr("class", "label")
                .attr("x", function (d) {
                    return -10;
                })
                .attr("y", groupHeight / 2)
                .attr("dy", ".35em")
                .text(function (d, i) {
                    if (i % data.series.length === 0) {
                        return data.labels[Math.floor(i / data.series.length)];
                    } else {
                        return "";
                    }
                });

            chart.append("g")
                .attr("class", "y axis")
                .attr("transform", "translate(" + spaceForLabels + ", " + -gapBetweenGroups / 2 + ")")
                .call(yAxis);
        }

        drawBarChart();

            }    
        };

    });

The problem is, when I am referencing this directive twice in the HTML, like this:

<bar-chart chart-data="chartData"></bar-chart>
<bar-chart chart-data="chartData"></bar-chart>

The chart is being created only 'once' (the second chart element is created but no chart is generated. 在此处输入图片说明

Also, even if I try to create another directive with different name but same code and same template, the first directive works and second directive doesn't.

<bar-chart chart-data="chartData"></bar-chart>
<bar-chart2 chart-data="chartData"></bar-chart2>

As you can see in link, you must get svg element from element parameter of directive. Check this plunker https://plnkr.co/edit/TlTJWDfTPAWa1sDPQM7w?p=preview (sorry for problem of width and x). In the plunker I get svg element as :

chart = d3.select(rawSvg[0])...

and not

chart = d3.select(".chart")...

With this you can put multiple charts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM