首页 > 其他分享 >如何在 AngularJS 中使用 Chart.js?

如何在 AngularJS 中使用 Chart.js?

时间:2024-07-26 13:27:47浏览次数:9  
标签:const rgba sampleData Chart js item AngularJS scope Payment

Chart.js 是一个灵活且功能强大的 JavaScript 库,可轻松创建各种类型的图表。在本指南中,我们将逐步介绍如何将 Chart.js 与 AngularJS 集成,并使用示例财务数据创建不同类型的图表。

一.先决条件

在我们开始之前,请确保您已准备好以下内容。

  • 已安装 Node.js
  • 您的项目中包含 AngularJS 库

二.使用

步骤 1. 设置 AngularJS 项目

如果您没有现有的 AngularJS 项目,请创建一个新项目。确保在项目中包含 AngularJS 和 Chart.js 库。

您可以在 HTML 文件中包括 AngularJS 和 Chart.js,如下所示。

<!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>

步骤 2.创建 AngularJS 控制器

在您的 app.js 中,创建一个 AngularJS 模块和一个控制器来处理图表:

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();
  }]);

步骤 3.添加样式

您可以添加样式来自定义图表的外观。将以下 CSS 添加到您的项目中:

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

步骤 4.运行应用程序

在 Web 浏览器中打开 index.html 文件。您应该会看到随示例数据显示的不同类型的图表。

三.结论

通过遵循这些步骤,您可以将 Chart.js 集成到 AngularJS 应用程序中,并创建各种类型的图表来可视化您的数据。Chart.js 提供了一种强大而灵活的方式来使用交互式且视觉上有吸引力的图表来增强您的 Web 应用程序。

标签:const,rgba,sampleData,Chart,js,item,AngularJS,scope,Payment
From: https://blog.csdn.net/xiefeng240601/article/details/140680386

相关文章

  • windows的nodejs版本控制工具:nvm nodejs以及vue的安装
    首先确保自己的电脑是首次安装nodejs相关的软件,安装nvm之前必须确保电脑无nodejs。1.nvm的安装在github上寻找合适的版本,我安装的是v1.12版本。Releases·coreybutler/nvm-windows·GitHubwindows下就下载如下图所示的nvm-setup.exe文件选择nvm的安装路径选择nodej......
  • js格式化金额 - 数字千分化
    /***格式化金额-数字千分化*@param{number|string}num-输入的数字或字符串*@returns{string}-格式化后的金额字符串,空值时返回'-'*/exportfunctionnumToMoney(num){//检查输入是否为空if(num===null||num===undefined||num===......
  • 什么是面向对象,js如何创建对象和工厂函数
    面向对象编程(Object-OrientedProgramming,简称OOP)是一种编程范式,它使用“对象”来设计软件。对象可以包含数据(属性)和代码(方法),这些代码可以操作这些数据。面向对象编程的基本概念包括:封装:把数据(属性)和行为(方法)组合在一起,隐藏内部状态和实现细节。继承:允许新创建的类(子类)继......
  • NodeJs 学习笔记
    Node.js是一个基于ChromeV8JavaScript引擎的开源运行环境,用于开发服务器端和网络应用。Node.js允许开发者使用JavaScript编写命令行工具和服务器端的应用程序,并且可以无缝地在从服务器到桌面应用再到移动设备的各种环境中运行。Node.js的核心原理包括:事件驱动:Node.......
  • (Javaweb)js
    目录一.js介绍二.引入方式三.js基础语法1.书写语法2.js变量3.数据类型运算符流程控制语句 四.js函数五.js对象六.js对象--Array数组七js对象--String字符串八.js对象--JSON九.js对象--BOM十.js对象--DOMDOM案例一.js介绍脚本语言:代码不需要进行编译,直......
  • 无法访问 json 属性
    我正在尝试访问此json的“城市”属性,但不知何故它不起作用,这是json结构:"{\"ForSaleShopperPlatformFullRenderQuery{\\\"zpid\\\":28657235,\\\"platform\\\":\\\"DESKTOP_WEB\\\",\\\"formType\\\":\\\"OPA......
  • 尝试解析文件中的多个 JSON 时字符索引不一致
    我使用以下代码来解析.json文件中存储的流中以逗号分隔的JSON多行对象:defstream_read_json(fn):importjsonstart_pos=0withopen(fn,'r',encoding='utf-8')asf:whileTrue:try:obj=json.load(f)yieldobj......
  • JavaWeb笔记_JSTL标签库&JavaEE三层架构案例
    一.JSTL标签库1.1JSTL概述 JSTL(jspstandardtaglibrary):JSP标准标签库,它是针对EL表达式一个扩展,通过JSTL标签库与EL表达式结合可以完成更强大的功能  JSTL它是一种标签语言,JSTL不是JSP内置标签  JSTL标签库主要包含:   ****核心标签     ......
  • 一篇文章讲清楚html css js三件套之html
    目录HTMLHTML发展史HTML概念和语法常见的HTML标签: HTML调试错误信息分析HTML文档结构HTML5的新特性结论HTMLHTML是网页的基础,它是一种标记语言,用于定义网页的结构和内容。HTML标签告诉浏览器如何显示网页元素,例如段落、标题、列表、链接、图片和表格等。HTML发......
  • GeoTools 读取 GeoPackage (`.gpkg`) 文件转为 GeoJSON
    要使用GeoTools读取GeoPackage(.gpkg)文件的第一个图层并将其转换为GeoJSON字符串,可以按照以下步骤进行:读取GeoPackage文件:使用GeoTools的DataStore类来访问GeoPackage文件。获取第一个图层:从DataStore中获取图层信息。将图层数据转换为GeoJSON:使用Featur......