如何在指令中 use/sync 控制器的数据?

How to use/sync data of controller in a directive?

经过一些研究,我找不到问题的答案。

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

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

我想在使用 D3JS 创建图表的指令中使用 $scope.salesData。

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>

问题是指令中根本没有检索到数据。我收到错误:无法读取未定义的 属性 'length'。 如果我对控制器中的值进行硬编码,它将起作用。

大家有什么建议吗?抱歉,如果我错过了另一个 post 的答案,我没有看到任何像我这样的案例。

这是一个同步问题。你的指令是在你的服务 returns 数据之前编译的,所以 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