How To Use Chart.js in AngularJS?

Chart.js is a flexible and powerful JavaScript library that makes it easy to create various types of charts. In this guide, we'll walk through the steps to integrate Chart.js with AngularJS and create different types of charts using sample financial data.

Prerequisites

Before we start, ensure you have the following.

  • Node.js installed
  • AngularJS library included in your project

Step 1. Setting up an AngularJS Project

If you don't have an existing AngularJS project, create a new one. Make sure you include AngularJS and Chart.js libraries in your project.

You can include AngularJS and Chart.js in your HTML file as follows.

<!DOCTYPE html>
<html ng-app="chartApp">
<head>
  <title>Chart.js with AngularJS</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <div ng-controller="ChartController as ctrl">
    <!-- Bar Chart: Receivables vs. Received Amounts -->
    <h2>Receivables vs. Received Amounts</h2>
    <canvas id="receivablesVsReceivedChart" width="400" height="200"></canvas>
    <!-- Pie Chart: Payment Status Distribution -->
    <h2>Payment Status Distribution</h2>
    <canvas id="paymentStatusChart" width="400" height="200"></canvas>
    <!-- Line Chart: Due Amount Over Time -->
    <h2>Due Amount Over Time</h2>
    <canvas id="dueAmountOverTimeChart" width="400" height="200"></canvas>
    <!-- Stacked Bar Chart: Comparison of Receivables, Received, and Due Amounts -->
    <h2>Comparison of Receivables, Received, and Due Amounts</h2>
    <canvas id="stackedBarChart" width="400" height="200"></canvas>
    <!-- Heat Map: Days Since Last Payment -->
    <h2>Days Since Last Payment (Heat Map)</h2>
    <canvas id="heatMapChart" width="400" height="200"></canvas>
  </div>
  <script src="app.js"></script>
</body>
</html>

Step 2. Creating the AngularJS Controller

In your app.js, create an AngularJS module and a controller to handle the charts:

angular.module('chartApp', [])
  .controller('ChartController', ['$scope', function($scope) {
    
    $scope.sampleData = [
      { hoseNo: 'H001', total_Receivable: 1000, total_Received: 700, due_Amount: 300, status: 'pending', last_Payment_Date: '2024-07-01', last_Payment_Days: 10 },
      { hoseNo: 'H002', total_Receivable: 1500, total_Received: 1500, due_Amount: 0, status: 'completed', last_Payment_Date: '2024-06-25', last_Payment_Days: 16 },
      { hoseNo: 'H003', total_Receivable: 1200, total_Received: 1000, due_Amount: 200, status: 'pending', last_Payment_Date: '2024-06-30', last_Payment_Days: 11 },
      { hoseNo: 'H004', total_Receivable: 1800, total_Received: 1800, due_Amount: 0, status: 'completed', last_Payment_Date: '2024-07-05', last_Payment_Days: 6 },
      { hoseNo: 'H005', total_Receivable: 1300, total_Received: 900, due_Amount: 400, status: 'pending', last_Payment_Date: '2024-07-02', last_Payment_Days: 9 }
    ];
    $scope.initCharts = function() {
      $scope.initBarChart();
      $scope.initPieChart();
      $scope.initLineChart();
      $scope.initStackedBarChart();
      $scope.initHeatMapChart();
    };
    $scope.initBarChart = function() {
      const ctx = document.getElementById('receivablesVsReceivedChart').getContext('2d');
      const labels = $scope.sampleData.map(item => item.hoseNo);
      const receivableData = $scope.sampleData.map(item => item.total_Receivable);
      const receivedData = $scope.sampleData.map(item => item.total_Received);
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [
            {
              label: 'Total Receivable',
              data: receivableData,
              backgroundColor: 'rgba(75, 192, 192, 0.2)',
              borderColor: 'rgba(75, 192, 192, 1)',
              borderWidth: 1
            },
            {
              label: 'Total Received',
              data: receivedData,
              backgroundColor: 'rgba(153, 102, 255, 0.2)',
              borderColor: 'rgba(153, 102, 255, 1)',
              borderWidth: 1
            }
          ]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    };
    $scope.initPieChart = function() {
      const ctx = document.getElementById('paymentStatusChart').getContext('2d');
      const pendingCount = $scope.sampleData.filter(item => item.status === 'pending').length;
      const completedCount = $scope.sampleData.filter(item => item.status === 'completed').length;
      new Chart(ctx, {
        type: 'pie',
        data: {
          labels: ['Pending', 'Completed'],
          datasets: [{
            data: [pendingCount, completedCount],
            backgroundColor: ['rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)'],
            borderColor: ['rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)'],
            borderWidth: 1
          }]
        }
      });
    };
    $scope.initLineChart = function() {
      const ctx = document.getElementById('dueAmountOverTimeChart').getContext('2d');
      const labels = $scope.sampleData.map(item => item.last_Payment_Date);
      const dueAmountData = $scope.sampleData.map(item => item.due_Amount);
      new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
            label: 'Due Amount',
            data: dueAmountData,
            backgroundColor: 'rgba(255, 159, 64, 0.2)',
            borderColor: 'rgba(255, 159, 64, 1)',
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    };
    $scope.initStackedBarChart = function() {
      const ctx = document.getElementById('stackedBarChart').getContext('2d');
      const labels = $scope.sampleData.map(item => item.hoseNo);
      const receivableData = $scope.sampleData.map(item => item.total_Receivable);
      const receivedData = $scope.sampleData.map(item => item.total_Received);
      const dueAmountData = $scope.sampleData.map(item => item.due_Amount);
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [
            {
              label: 'Total Receivable',
              data: receivableData,
              backgroundColor: 'rgba(75, 192, 192, 0.2)',
              borderColor: 'rgba(75, 192, 192, 1)',
              borderWidth: 1
            },
            {
              label: 'Total Received',
              data: receivedData,
              backgroundColor: 'rgba(153, 102, 255, 0.2)',
              borderColor: 'rgba(153, 102, 255, 1)',
              borderWidth: 1
            },
            {
              label: 'Due Amount',
              data: dueAmountData,
              backgroundColor: 'rgba(255, 159, 64, 0.2)',
              borderColor: 'rgba(255, 159, 64, 1)',
              borderWidth: 1
            }
          ]
        },
        options: {
          scales: {
            x: {
              stacked: true
            },
            y: {
              stacked: true,
              beginAtZero: true
            }
          }
        }
      });
    };
    $scope.initHeatMapChart = function() {
      const ctx = document.getElementById('heatMapChart').getContext('2d');
      const labels = $scope.sampleData.map(item => item.hoseNo);
      const paymentDaysData = $scope.sampleData.map(item => item.last_Payment_Days);
      const colors = $scope.sampleData.map(item => {
        if (item.last_Payment_Days < 10) return 'rgba(75, 192, 192, 0.2)';
        if (item.last_Payment_Days < 20) return 'rgba(255, 205, 86, 0.2)';
        return 'rgba(255, 99, 132, 0.2)';
      });
      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: labels,
          datasets: [{
            label: 'Days Since Last Payment',
            data: paymentDaysData,
            backgroundColor: colors,
            borderColor: colors.map(color => color.replace('0.2', '1')),
            borderWidth: 1
          }]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true
            }
          }
        }
      });
    };
    $scope.initCharts();
  }]);

Step 3. Adding Styles

You can add styles to customize the appearance of your charts. Add the following CSS to your project:

canvas {
  display: block;
  margin: 0 auto;
}

Step 4. Running the Application

Open your index.html file in a web browser. You should see the different types of charts displayed with the sample data.

Chart Displayed

Amount

Chart

Over time

Due Ammount

Conclusion

By following these steps, you can integrate Chart.js into your AngularJS application and create various types of charts to visualize your data. Chart.js provides a powerful and flexible way to enhance your web applications with interactive and visually appealing charts.


Similar Articles