2016-09-28 83 views
0

我創建了一個顯示圖表的簡單指令。角度js指令作用域值與控制器綁定undefined

我有一個$ http請求的角度指令。我必須將響應存儲到我的$ scope中,並將此$ scope值存儲到我的鏈接指令範圍中以顯示圖表。

我試圖使用上午圖表角度圖

這裏實施軌距圖表是我的代碼:

app.directive('gauge',function(){ 
    return { 
     restrict: 'AEC', 
     replace:true, 
     template: '<div id="speeda_meter"></div>', 
     scope: {ranges:'='}, 
     controller: function ($scope, $http,apiurl) { 
      $scope.type = 'percentage'; 
      function getUsage(type){ 
       $http({ 
        method: 'POST', 
        url: apiurl + '/getUsage', 
        data: {'type': $scope.type} 
       }).success(function (data, status) { 
        if (data.status == true) { 
         $scope.ranges = data.result.ranges; 
         $scope.interval = data.result.interval; 
        }  
       }); 
      }  
      getUsage($scope.type); 

     }, 
     link: function (scope, element, attrs,ctrl) { 
      var chart = false;    
     //  ngModelCtrl.$formatters.push(function(modelValue) { 
     //   return modelValue; 
      // }); 

      // ngModelCtrl.$render = function() { 

       //scope.ranges = ngModelCtrl.$viewValue; 
       console.log(ctrl.ranges); 
       var initChart = function() { 
        if (chart) chart.destroy(); 
        var config = scope.config || {}; 
        chart = AmCharts.makeChart("speeda_meter", { 
          "type": "gauge", 
          "axes": [ { 
           "axisThickness": 0, 
           "axisAlpha": 0.2, 
           "tickAlpha": 0.2, 
           "valueInterval": 425, 
           "inside": false, 
           "fontSize": 11, 
           "gridInside": true, 
           "startAngle": -90, 
           "endAngle": 90, 
           "bands": scope.ranges, 
           "topText": "497", 
           "topTextYOffset": 105, 
           "topTextColor": "#555555", 
           "topTextFontSize": 50, 
           "bottomText": "Watts", 
           "bottomTextYOffset": -10, 
           "bottomTextColor": "#909090", 
           "bottomTextFontSize": 18, 
           "endValue": 1700 
          }], 
          "arrows": [{ 
           "startWidth" : 15, 
           "nailBorderThickness" : 1, 
           "nailRadius" : 8 , 
           "color" : "#5b5b5b", 
          }], 
          "export": {"enabled": true} 
        });   
       }; 
       initChart();  
      // }    
     }   
    } 
}); 

<gauge ranges="ranges" interval="interval"></gauge> 

我試圖範圍和間隔與所述響應於在所述鏈路分配範圍,但它是未定義的。那有什麼問題?

任何解決方案?

回答

0

您正試圖爲異步調用後分配一個值。 當你的amhchart被渲染時,它將獲取該特定實例的值,並且不會給你像角度do那樣的兩種方式綁定的能力。因此,當執行init函數時,沒有$ scope.ranges的值,它們在圖表。

你應該呈現圖表調用完成後,像這樣

function getUsage(type){ 
      $http({ 
       method: 'POST', 
       url: apiurl + '/getUsage', 
       data: {'type': $scope.type} 
      }).success(function (data, status) { 
       if (data.status == true) { 
        $scope.ranges = data.result.ranges; 
        $scope.interval = data.result.interval; 

        initChart()//call the chart rendering here 
       }  
      }); 
     }  
     getUsage($scope.type); 

或至少當通話結束

重繪