Jeff
Jeff

Reputation: 1

Angular-chart.js click on bar and change it's background color

I'm using angular-chart.js to paint a simple bar chart, when I click the bar ,how to change background color?

 $scope.click = function (points, evt) {
    // console.log(points,evt);
};

Upvotes: 0

Views: 1207

Answers (2)

AmberJ
AmberJ

Reputation: 1

For the people working with legacy code like myself... I have an answer to this.

With angular-chart.js, use the chart-dataset-override property. With this, you can set the borderColor to accept an array, representing each data index.

<canvas id="myBarChart" 
               class="chart chart-bar"
               chart-colors="colors"
               chart-data="data" 
               chart-labels="labels"
               chart-series="series"
               chart-options="options"
               chart-click="onClick"
               chart-dataset-override="datasetOverride" // <--- what you want
</canvas>

This is how I defined mine:

 $scope.datasetOverride =  [
                            {
                             borderWidth: [0, 0, 0, 0, 0, 0, 0], // defaults to no border
                             borderColor: "rgb(225, 225, 225)", // white
                            }
                            // can add more objects here for other datasets
                           ];

Grab a reference to your chart from an 'on-create' event like so:

$scope.$on('chart-create', function (evt, chart) {
            $scope.chart = chart;
        });

Then use a conditional in your click event function to set the increase the border, using the event index. If so, I changed all 4 of these properties.

element[0]._model.borderWidth = 10;
element[0]._chart.config.data.datasets.borderWidth[barIndex] = 10;
element[0]._view.borderWidth = 10;
$scope.datasetOverride[0].borderWidth[element[0]._index] = 10; // something like this

Then reference that chart and call the update trigger at the end of your click function.

$scope.chart.update();

Magic. Grabbing on to the update method will create a smoother change in your graph than $scope.$apply()

Hope this helps someone! Cheers.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222722

You can do this onClick

 onClick: (point, elements) => {
      if (elements && elements.length) {
        var segment = elements[0];
        segment._model.backgroundColor = "#f6954d"

        $scope.colors[segment._index] = "#f6954d";
        $scope.$apply();
      }
    }

DEMO

Upvotes: 1

Related Questions