如何在指令中使用/同步控制器的数据?

经过一番调查,我无法find我的问题的答案。

我有一个从数据库中获取数据的控制器,我把一些数据放在一个表中(在其他地方使用)。

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创build一个图表。

 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> 

问题是数据在指令中根本没有被检索到。 我有错误:不能读取未定义的属性“长度”。 如果我硬编码控制器中的值,它将工作。

任何build议家伙? 对不起,如果我错过了另一篇文章的答案,我没有看到像我的任何情况。

这是一个同步问题。 您的指令是在服务返回数据之前编译的,因此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 ... }); } }; }); 

工作Plunk

您可以在这里了解更多有关$watchfunction的信息 。