如何为图例获取正确的自定义颜色

How to get the right custom color for legend

圆环图的自定义颜色未显示在图例中,而是图例采用任意颜色。我怎样才能让它拾取那些自定义颜色?

app.controller("ExampleController", ["$scope", function ($scope) {
        $scope.pie = [
            {key: "Passed", y: 2},
            {key: "Failed", y: 3}
        ];

        var colorArray = ['red', 'green'];
        $scope.colorFunction = function() {
            return function(d, i) {
                return colorArray[i];
            };
        };
        ...x y functions ...
}]);

HTML

...
    <nvd3-pie-chart
            data="pie"
            id="donutLabelsOutsideExample"
            width="450"
            height="350"
            x="xFunction()"
            y="yFunction()"
            donut="true"
            showLabels="true"
            showLegend="true"
            donutLabelsOutside="true"
            labelType="percent"
            color="colorFunction()">
        <svg height="250"></svg>
    </nvd3-pie-chart>
...

饼图的 source code 包含 legendcolor 的属性,因此您可以尝试添加该属性。

legendcolor="colorFunction()"

为什么有效:

  1. pieChart 的控制器中有一个对 checkElementID 的调用,后者又调用 configureLegend
  2. configureLegendsource code 中找到并具有以下代码

chart.legend.color(attrs.legendcolor === undefined ? nv.utils.defaultColor() : scope.legendcolor());

attrs.legendcolor 是从您的指令属性中提取的。