You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中ng-model绑定值无法获取,图表数据空白求助

解决Angular中获取ng-model值渲染ApexCharts无数据的问题

问题根源

  1. ng-model绑定错误:你给ng-model写了字面量10,Angular的ng-model必须绑定到$scope上的变量,不能直接写固定值,否则双向绑定失效。
  2. DOM操作不符合Angular逻辑:用document.getElementById获取input值是原生JS的做法,违背了Angular数据驱动的理念,而且控制器初始化时,Angular可能还没完成数据绑定,导致拿到空值。
  3. 数据类型不匹配:input的value是字符串类型,ApexCharts的series需要数值类型,直接传入字符串会导致图表无法渲染数据。

修正后的代码

HTML部分

<input type="text" id="totalscore2" ng-model="totalScore" value="10">
<div id="charttest"></div>

JavaScript部分

angular.module('teB', [])
 .controller('teBB', ['$scope', function($scope) {
  // 初始化$scope变量,设置初始分值
  $scope.totalScore = 10;

  // 将值转为数值类型,适配ApexCharts的要求
  let total = Number($scope.totalScore);
  
  const options = {
    series: [total],
    chart: {
      height: 350,
      type: 'radialBar',
    },
    plotOptions: {
      radialBar: {
        hollow: {
          size: '70%',
        }
      },
    },
    labels: ['Puntuación'],
  }

  let chart = new ApexCharts(document.querySelector("#charttest"), options);
  chart.render();

  // 实时监听分值变化,自动更新图表
  $scope.$watch('totalScore', function(newVal) {
    chart.updateSeries([Number(newVal)]);
  });
 }]);

说明

  • 把ng-model绑定到$scope.totalScore,让Angular管理数据绑定,初始值通过$scope设置,也可以在input的value属性里设置。
  • 从$scope直接获取变量值,转成Number类型,确保ApexCharts能正确识别数据。
  • 添加$watch监听变量变化,当input里的数值修改时,图表会自动更新,全程不用手动操作DOM,符合Angular的开发规范。

内容的提问来源于stack exchange,提问作者Adrian Miguel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:01:13