Modify KendoUI Donut chart series label color to match the series color

Currently, I am utilizing kendoUI in combination with angular to create a Kendo Donut chart. Below is the representation of my chart.

<div class="center-pad" kendo-chart k-theme="['material']" k-chart-area="{height: 325, width: 480}" 
     k-series="[{ type: 'donut',
                  field: 'percentage',
                  labels: {visible: true, template: '${value} ${category} ${dataItem.color}', position: 'outsideEnd',  font: '15px Lato-Regular'},
                  categoryField: 'source',
                  explodeField: 'explode'}]" 
                  k-series-click="actionChartClick" k-data-source="actionChartData">

My goal is to synchronize the series label color with the respective series color. Within the template, I can access the color using ${dataItem.color}.

I attempted to achieve this by adjusting the settings as follows:

k-series="[{ ...
              labels: {visible: true, template: '${value} ${category}', position: 'outsideEnd', font: '15px Lato-Regular', color: '${dataItem.color}'}"

However, this approach did not yield desired results. Would appreciate any guidance on the correct modification required for achieving this?

Answer №1

To set the color in your chart, utilize either seriesDefaults.labels.color or series.labels.color and specify the desired color value within a function. This function will have access to both the series and dataItem as arguments.

http://docs.telerik.com/kendo-ui/api/javascript/dataviz/ui/chart#configuration-series.labels.color

<!DOCTYPE html>
<html>
  <head>
    <base href="http://demos.telerik.com/kendo-ui/donut-charts/donut-labels">
    <style>html { font-size: 14px; font-family: Arial, Helvetica, sans-serif; }</style>
    <title></title>
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css" />
    <link rel="stylesheet" href="//kendo.cdn.telerik.com/2016.3.914/styles/kendo.default.min.css" />

    <script src="//kendo.cdn.telerik.com/2016.3.914/js/jquery.min.js"></script>
    <script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>
  </head>
  <body>
    <div id="chart"></div>

    <script>

      $(function() {
        $("#chart").kendoChart({
          title: {
            text: "Select Your Preferred Sport"
          },
          legend: {
            position: "top"
          },
          seriesDefaults: {
            labels: {
              template: "#= category # - #= kendo.format('{0:P}', percentage)#",
              position: "outsideEnd",
              visible: true,
              background: "transparent",
              color: function(e) {
                // e.series
                // e.dataItem
                if (e.category == "Football") {
                  return "#000";
                } else {
                  return e.series.color;
                }
              }
            }
          },
          series: [{
            type: "donut",
            labels: {
              /*color: function(e) {
                // e.series
                // e.dataItem
                if (e.category == "Football") {
                  return "#f00";
                } else {
                  return e.series.color;
                }
              }*/
            },
            data: [{
              category: "Football",
              value: 35
            }, {
              category: "Basketball",
              value: 25
            }, {
              category: "Volleyball",
              value: 20
            }, {
              category: "Rugby",
              value: 10
            }, {
              category: "Tennis",
              value: 10
            }]
          }],
          tooltip: {
            visible: true,
            template: "#= category # - #= kendo.format('{0:P}', percentage) #"
          }
        });

      });

    </script>

  </body>
</html>

Answer №2

I have discovered a solution that involves utilizing k-options.

<div class="center-pad" kendo-chart k-theme="['material']" k-chart-area="{height: 325, width: 480}" 
 k-series="[{ type: 'donut',
              field: 'percentage',
              labels: {visible: true, template: '${value} ${category} ${dataItem.color}', position: 'outsideEnd',  font: '15px Lato-Regular'},
              categoryField: 'source',
              explodeField: 'explode'}]" 
              k-series-click="actionChartClick" k-data-source="actionChartData"
              k-options="chartOptions">

In the controller, include the following:

$scope.chartOptions = {
                dataBound: function(e) {
                    e.sender.options.series[0].labels.color = function(element) {
                        return element.dataItem.color;
                    }
                }
            };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AJAX successfully completes, but no response is received

I've been struggling to get the success function in my AJAX call to trigger. I know everything is set up correctly because when I make a request to my API, I can see that it's hitting the URL and the server is responding with an HTTP 200 status. ...

obtaining specific information from JSON data

In my JavaScript code, I am retrieving data from an ajax call: $.ajax({ type: "GET", url: URL, headers: { 'Access-Control-Allow-Origin': '*' }, async: false, dataType: "text", succes ...

jQuery post method not transmitting POST data successfully

const link = 'http://www.example.com/maketransaction.php?validate=1&key=123'; const amount = 50; const userID = 5; const requestData = {transactionAmount:amount, ID:userID, tag:null}; $(document).ready(function(){ $.ajax({ 'u ...

Ensure that the promise is fulfilled only if a specific condition is met

I have a complex if-else condition in my code that includes different promises. Once the logic determines which condition to enter and executes the corresponding promise, I need to ensure that a final promise is always executed. if (a < 5) { vm.pr ...

Several instances of TinyMCE not displaying correctly upon initialization

I am currently utilizing TinyMce with the ui-tinymce Package. Initially, I had multiple TinyMce instances generated through the ng-repeat in a table, and everything was functioning as expected. However, for comparison purposes, I decided to have the ng-r ...

Unable to direct to the main page in index.js of the next.js application

I have been working on a next.js application and encountered an issue with a component I created called <ButtonGroup>. I added a button with the code <Button href="index">Home</Button> to allow users to navigate back to the home ...

Resize an image to precisely match the height of the text automatically

I am facing a challenge where I want to embed an image inline with text, while ensuring that it matches the height of the text. I have tried using <img src="img.jpg" height=16> and also <img src="img.jpg" height="100%">, but the former does not ...

The Angular controller method is returning an outdated value from the scope

My Objective: In my project, I am developing a directive that includes an input text field. The directive takes in a value and an onChange method as scope parameters. There is also a controller wrapped around this directive in the HTML code provided. Thi ...

CSS for Mobile Devices: How to Properly Position Backgrounds

My website has an image named background.jpg that displays correctly on desktop but looks odd on mobile screen sizes. How can I modify my stylesheet.css to reduce the size of the image so it appears similar to how it does on desktop? Current code: #servi ...

Angular - efficiently trims the array by removing everything except the required object

I'm having trouble removing contacts from my Phonebook app. Every time I use the deletePerson function, it deletes all contacts except the one I want to remove. Can someone please help me identify where I'm going wrong? Here is a snippet of my c ...

Retrieve, establish cookies, and guard against CSRF attacks

Having some difficulty with CSRF in my application while using Isomorphic fetch. The backend sends a CSRF-TOKEN in the set-cookies property: https://i.sstatic.net/duODj.png There is advice against directly accessing these cookies in code, so I attempted ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Obtaining an array from a split string with negative values may be achieved by following these steps

I'm struggling to find the right approach here. Can someone help me convert the number -800 into [-8, 0, 0]? To start, I turned the number into a string and used the map function to create an array: const number = -800; const numberString = numbe ...

Guide on transforming OBJ/FBX files into GLTF format prior to adding them to your scene with Threejs

Currently, I am working on developing a web application that allows users to upload obj/fbx files and view them directly in the browser. The utilization of OBJLoader and FBXLoader provided by Threejs has been successful so far. However, I have a specific r ...

What is the process for determining the estimated location of a queued event within a JavaScript Engine's event queue?

Imagine a multitude of events being created and added to the event queue of a Javascript engine. Are there any techniques or recommended practices in the industry to predict the order in which a specific event will be added to the queue? Any knowledge or ...

Tips for activating animated text upon hovering over a text or image:

My brand name is: Code The navigation bar displays as follows: Code Home | Service | Product | Contact I would like to change the appearance of my brand name from Code to { Code } when users hover over it. Additionally, I wish to style the brackets { ...

Determine the number of occurrences of a specific object property within an array consisting of multiple objects

Currently, I am working on developing a lottery system using JavaScript and React to enhance my skills. One of the challenges I am facing is creating a function that can identify the most common bet combination in my betObject array and then list all the b ...

Retrieve element attributes and context inside a function invoked by an Angular directive

When working with a directive definition, you have access to the $element and $attrs APIs. These allow you to refer back to the element that called the directive. However, I'm curious how to access $element and $attrs when using a standard directive l ...

Why don't updates made in the database reflect in real time?

Currently, I am diving into the world of Firestore's real-time functionality. Below is a snippet of my code where I am fetching data: useEffect(() => { let temp = []; db.collection("users") .doc(userId) .onSnapshot((docs) =&g ...

Exploring the world of design patterns using three.js and webpack

Looking to improve the organization of my code with three.js and webpack rather than having everything in a single file (like camera, meshes, lights, postprocessing, etc). I had the idea of using "manager modules" such as a LightManager class or a PostPro ...