首页 > 解决方案 > TypeError:无法在 AngularJs 中读取 null 的属性(读取“长度”)

问题描述

我有这个 HTML 代码:

<div ng-repeat="(k,v) in device">
  <div class="panel-body m-5 p-5">
     <canvas id="@{{ k }}"></canvas>
  </div>
</div>

这是范围内的数据:

$scope.device = ['102','102','103','104','105'];

我正在循环使用“foreach”来根据设备显示图形:

angular.forEach($scope.device, function(item, i) {
  $scope.ctx = document.getElementById(i);
  $scope.myChart = new Chart($scope.ctx, {
    type: 'line',
    data: {
    labels: ['2021-08-10 08:00', '2021-08-10 09:00',
             '2021-08-10 10:00', '2021-08-10 11:00',
             '2021-08-10 12:00', '2021-08-10 13:00',
            ],
    datasets: [{
       backgroundColor: window.chartColors.red,
       borderColor: window.chartColors.red,
       borderWidth: 1,
       pointRadius: 2,
       lineTension: 0,
       fill: false,
       label: 'pH',
       data: [1, 2, 3, 4, 5, 6],
    }, {
       backgroundColor: window.chartColors.blue,
       borderColor: window.chartColors.blue,
       borderWidth: 1,
       pointRadius: 2,
       lineTension: 0,
       fill: false,
       label: 'TSS',
       data: [12, 11, 10, 9, 8, 7],
    }]
  },
  options: {
    responsive: true,
    title: { display: true},
    scales: {
      yAxes: [{
        ticks: { beginAtZero: true }
      }],
      xAxes: [{
        ticks: {}
      }]
    },
    legend: {
      labels: {
        boxWidth: 10,
        fontSize: 10
      }
    }
  },
});

});

为什么如果我在“foreach”之外写它会出现,而如果在“foreach”内部它总是显示错误(TypeError: Cannot read properties of null (reading 'length')

标签: javascriptangularjschart.js

解决方案


推荐阅读