2015-09-05 62 views
0

我怎么能在我的指令,而不是硬编码的实际数据传递JSON数据对象dataProvider来渲染图形与AmchartsAngularjs ? 如果提供的数据是JSON而不是JavaScript对象,则会渲染该图形,否则该图形根本不会渲染。虽然图表标题是可见的,但轴未创建,并且数据点也不显示在图中。Angularjs,Amcharts不JSON数据对象的工作被分配给数据提供商,而不是实际的数据

angular.module('myApp').directive('activityChart', 
    function ($timeout) { 
     return { 
     restrict: 'EA', 
     replace:true, 
     //scope :true, 
     template: '<div id="{{chartId}}" style="width: 100%; height: 400px; overflow: hidden; text-align: left;"></div>' , 
     link: function ($scope, $element, $attrs) { 

      var chart = false; 

      var initChart = function() { 
       if (chart) chart.destroy(); 
       $scope.chartId = $attrs.chartId; 
       $scope.chartUnit = $attrs.chartUnit; 
       $scope.chartData = $attrs.chartData; 
       console.log($scope.chartData); 
       $timeout(function(){var chart = AmCharts.makeChart($scope.chartId, { 
        "type": "serial", 
        "pathToImages": "/assets/amcharts/images/", 
        "categoryField": "time", 
        "dataDateFormat": "YYYY-MM-DD HH:NN:SS", 
        "categoryAxis": { 
         "minPeriod": "mm", 
         "parseDates": true 
        }, 
        "chartCursor": { 
         "categoryBalloonDateFormat": "JJ:NN:SS" 
        }, 
        "chartScrollbar": {}, 
        "trendLines": [], 
        "graphs": [ 
         { 
          "bullet": "round", 
          "bulletSize": 4, 
          "id": $scope.chartId, 
          "title": $scope.chartId, 
          "valueField": "value", 
          "type": "smoothedLine", 
          "lineThickness": 2, 
          "lineColor": "#637bb6" 
         } 
        ], 
        "guides": [], 
        "valueAxes": [ 
         { 
          "id": "ValueAxis-1", 
          "title": $scope.chartId + " (" + $scope.chartUnit + ")" 

         } 
        ], 
        "allLabels": [], 
        "balloon": {}, 
        "legend": { 
         "useGraphSettings": true 
        }, 
        "titles": [ 
         { 
          "id": "Title-1", 
          "size": 15, 
          "text": $scope.chartId 
         } 
        ], 
        "dataProvider": $scope.chartData, 
       }); 

       }); 

      }; 
      initChart(); 

     } 
    } 
}) ; 
+1

这个问题是关系到http://stackoverflow.com/questions/23009890/amcharts-with-angularjs –

+0

是否有必要有'chartId'作为元素ID? – gerric

+0

'chartUnit'从哪里来?捆绑? – gerric

回答

0

我为您的用例做了一个通用的演示。看看这个fiddle

关键是为你的指令引入一个隔离的范围。这使您可以多次使用该指令。

如果你不喜欢这样写道:

scope: { 
    // bi directional binding will pass data array to isolated scope 
    data: '=', 
    title: '@' 
}, 

可以将数据阵列从父控制器分配:

<activity-chart data="data" title="This is the title"></activity-chart> 

随意问,如果你不明白它是如何工作的。

相关问题