Implementing charts using Chart.js in AngularJS

Loading

Chart.js is a popular JavaScript library for creating interactive and visually appealing charts. It can be integrated with AngularJS to display dynamic data in applications. In this guide, we’ll cover the step-by-step implementation of Chart.js in an AngularJS application.


1. Prerequisites

Before integrating Chart.js, ensure that you have:

  • Basic knowledge of AngularJS
  • A working AngularJS application
  • Chart.js library installed

2. Installing Chart.js

A. Using a CDN (For Browser)

Add the following scripts to your index.html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>

B. Installing via NPM (For Node.js-based Projects)

npm install chart.js

3. Creating an AngularJS App and Controller

First, define an AngularJS module and a controller in your app.js file.

A. Define the AngularJS App

Create app.js with the following content:

var app = angular.module('chartApp', []);

B. Create a Controller to Handle Chart Data

Inside app.js, define a controller to store and manipulate chart data.

app.controller('ChartController', function ($scope) {
$scope.labels = ["January", "February", "March", "April", "May"];
$scope.data = [10, 20, 30, 40, 50];
});

4. Adding Chart.js to AngularJS Views

Now, modify the HTML file (index.html) to include the chart canvas.

A. Basic HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS with Chart.js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="chartApp" ng-controller="ChartController">
<div style="width: 60%; margin: auto;">
<canvas id="myChart"></canvas>
</div>

<script>
angular.module('chartApp').controller('ChartController', function ($scope) {
$scope.labels = ["January", "February", "March", "April", "May"];
$scope.data = [10, 20, 30, 40, 50];

setTimeout(function () {
var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'bar', // Change to 'line', 'pie', 'doughnut', etc.
data: {
labels: $scope.labels,
datasets: [{
label: 'Sales Data',
data: $scope.data,
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}, 100);
});
</script>
</body>
</html>

5. Explanation of Code

A. Setting Up AngularJS

  • We define an AngularJS app (chartApp) and a controller (ChartController).
  • Inside $scope, we define labels and data for the chart.

B. Integrating Chart.js

  • We select the canvas element using document.getElementById('myChart').
  • We create a Chart object using new Chart(ctx, {...}).
  • The type of chart can be changed (e.g., 'line', 'pie', 'doughnut').
  • Labels and data are assigned dynamically from $scope.labels and $scope.data.

C. Ensuring Proper Data Binding

  • setTimeout ensures that the chart is initialized after AngularJS binds the data.

6. Updating Chart Dynamically

If you need to update the chart dynamically when data changes, modify the controller:

app.controller('ChartController', function ($scope) {
$scope.labels = ["January", "February", "March", "April", "May"];
$scope.data = [10, 20, 30, 40, 50];

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: $scope.labels,
datasets: [{
label: 'Sales Data',
data: $scope.data,
backgroundColor: 'rgba(75, 192, 192, 0.5)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});

$scope.updateChart = function () {
$scope.data = [50, 40, 30, 20, 10]; // New data
myChart.data.datasets[0].data = $scope.data;
myChart.update();
};
});

Modify HTML to Include Update Button

<button ng-click="updateChart()">Update Chart</button>

This allows users to dynamically update the chart when the button is clicked.


7. Different Chart Types in Chart.js

Change the type in the Chart object to create different charts.

A. Line Chart

type: 'line'

B. Pie Chart

type: 'pie'

C. Doughnut Chart

type: 'doughnut'

D. Radar Chart

type: 'radar'

8. Handling API Data with Chart.js in AngularJS

Instead of using static data, you can fetch dynamic data from an API.

A. Fetch Data Using $http

app.controller('ChartController', function ($scope, $http) {
$scope.labels = [];
$scope.data = [];

$http.get('https://api.example.com/chart-data').then(function (response) {
$scope.labels = response.data.labels;
$scope.data = response.data.values;

var ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: $scope.labels,
datasets: [{
label: 'API Data',
data: $scope.data,
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}]
}
});
});
});

This fetches data from an API and dynamically updates the chart.

Leave a Reply

Your email address will not be published. Required fields are marked *