简体   繁体   中英

How to align legend in angular-chart.js

II'm using an angular-chart.js chart-pie.

I need to align the legend like horizontalAlign: "right", verticalAlign: "center" , but I have no idea how to do it.


My code

HTML:

<canvas id="pie" class="chart chart-pie"
      chart-data="data" chart-labels="labels" chart-options="options">
</canvas>

Module:

angular.module("app", ["chart.js"]).controller("PieCtrl", function ($scope) {
    $scope.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales"];
    $scope.data = [300, 500, 100];
    $scope.options = { 
        legend : { 
            display : true, 
            position : "right"
        }
    };
});

Just add this style to your css:

.chart-container {
    position: relative;
}
chart-legend {
    position: absolute;
    top: 50%;
    right: 0%;
    transform: translateY(-50%);
}

I have edited my code. This will align your legend horizontally to the right and vertically in the middle.

Explanation:

The directive creates this html structure: 在此输入图像描述

You can add your own style to the elements.

Edit Put in html like this:

<style>
   .chart-container {
        position: relative;
    }
    chart-legend {
        position: absolute;
        top: 50%;
        right: 0%;
        transform: translateY(-50%);
    }
</style>

Edit 2.

The code above works for an older version. For the newer version open the Chart.js and add this code

y += me.height/2 - itemHeight*me.legendItems.length/2;

above

drawLegendBox(x, y, legendItem);

to be more exact on line 6553.

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