2017-07-15 50 views
-1

我有數組是這樣的:如何根據數組值創建餅圖?

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

我做模型的版本,所以我想只是爲了顯示餅圖這將有來自名從點的數據和標籤。

我做出這樣的:

<canvas id="pie" class="chart chart-pie" 
            chart-data="commonEstimationStats.rates.points" chart-labels="commonEstimationStats.rates.direction.name" chart-options="options"> 
          </canvas> 

,但它無法正常工作。

回答

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

DEMO

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="[email protected]*" 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>

+0

非常感謝你,它正在^^ – sopovar

+0

請把它標記爲答案,如果它幫助 – Sajeetharan