2015-04-07 31 views
1

經過一番研究,我無法找到我的問題的答案。如何在指令中使用/同步控制器的數據?

我有一個控制器從數據庫中獲取數據,並且我把一些數據放在一個表中(用在其他地方)。

Employees.getEmployees() // A service that return $http.get ... 
     .success(function(data) {    
      $scope.employees = data;   
     }); 

$scope.salesData = []; 
angular.forEach($scope.employees,function(employees){ 
    $scope.salesData.push(employees.totalSales); 
}); 

我想在一個指令中使用這個$ scope.salesData,它創建了一個帶有D3JS的圖表。

angular.module('dirDonut', []) 
.directive("linearChart", function($window) { 
return{ 
    restrict: "EA", 
    link: function(scope, el, attrs){ 

     // retrieve datas from the Controller 
     var data=scope[attrs.chartData]; 

     // Here the code creates the chart ... 
    } 
    }; 
}); 

然後,在HTML:

<div linear-chart chart-data="salesData"></div> 

的問題是,DATAS未在指令中檢索到的所有。我有錯誤:無法讀取未定義的屬性「長度」。 如果我硬編碼控制器中的值,它將起作用。

任何建議傢伙?對不起,如果我錯過了另一篇文章的答案,我沒有看到像我的任何情況。

回答

1

這是一個同步問題。您的指令在服務返回數據之前編譯,因此scope[attrs.charData]未定義。

你需要做的是等待數據變爲可用:

app.directive("linearChart", function($window) { 
    return{ 
     restrict: "EA", 
     link: function(scope, el, attrs){ 
      scope.$watch(function() { 
       return scope[attrs.chartData]; 
      }, function(value) { 
       var data = value; 
       // Here the code creates the chart ... 
      });  
     } 
    }; 
}); 

Working Plunk

您可以瞭解更多有關$watch功能here

+0

感謝邁克爾的答案。但我還有一個問題。我試圖從$ scope.employees中創建一組數據。 angular.foreach()似乎不起作用。 – adnpwd

+0

由於你的指令沒有這個原因,它不起作用。您需要將該代碼移入「成功」回調。 –

相關問題