如何从数组值制作饼图?

时间:2017-07-15 07:29:15

标签: angularjs chart.js

我有这样的数组:

C.BRowType

我制作模型版本,所以我只想显示饼图,其中包含来自名称的点和标签的数据。

我这样做:

$scope.commonEstimationStats = {
                rates: [
                    {
                        "direction": {
                            "id": 13,
                            "name": "health",
                            "type": 1
                        },
                        "points": 5
                    },
                    {
                        "direction": {
                            "id": 14,
                            "name": "education",
                            "type": 1
                        },
                        "points": 3
                    }, ....

但它不起作用。

1 个答案:

答案 0 :(得分:1)

您可以使用angular.Foreach生成标签和数据。

    $scope.labels = [];
    $scope.data = [];
    angular.forEach($scope.commonEstimationStats.rates, function(key, value) {
      $scope.labels.push(key.direction.name);
      $scope.data.push(key.points);
    })

<强>样本

angular.module("app", ["chart.js"])
  .controller("BarCtrl", function($scope) {
    $scope.commonEstimationStats = {
      rates: [{
        "direction": {
          "id": 13,
          "name": "health",
          "type": 1
        },
        "points": 5
      }, {
        "direction": {
          "id": 14,
          "name": "education",
          "type": 1
        },
        "points": 3
      }]
    };
    $scope.labels = [];
    $scope.data = [];
    angular.forEach($scope.commonEstimationStats.rates, function(key, value) {
      $scope.labels.push(key.direction.name);
      $scope.data.push(key.points);
    })
    $scope.datasetOverride = [{
      fill: true,
      backgroundColor: [
        "#66ff33",
        "#36A2EB",
        "#FFCE56"
      ]
    }, {
      fill: true,
      backgroundColor: [
        "#ffff00",
        "#46BFBD",
        "#FDB45C"
      ]
    }];
  });
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script data-require="jquery@*" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
  <script src="https://opensource.keycdn.com/angularjs/1.5.8/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.0/Chart.min.js"></script>
  <script src="//cdn.jsdelivr.net/angular.chartjs/latest/angular-chart.min.js"></script>  
</head>
<body>
  <div ng-controller="BarCtrl">
    <canvas id="bar" class="chart chart-pie" chart-data="data" chart-dataset-override="datasetOverride" chart-series="series" chart-labels="labels"></canvas>
  </div>
</body>
</html>