经过一番研究,我无法找到问题的答案。
我有一个从数据库获取数据的 Controller ,并将一些数据放入表中(以在其他地方使用)。
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>
问题是指令中根本没有检索到数据。我收到错误:无法读取未定义的属性“长度”。 如果我对 Controller 中的值进行硬编码,它将起作用。
大家有什么建议吗?抱歉,如果我错过了另一篇文章中的答案,我没有看到像我这样的案例。
最佳答案
这是一个同步问题。您的指令是在服务返回数据之前编译的,因此 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 ...
});
}
};
});
您可以了解有关$watch
函数的更多信息here .
关于angularjs - 如何在指令中使用/同步 Controller 的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29496268/