angularjs - 如何在指令中使用/同步 Controller 的数据?

标签 angularjs node.js angularjs-directive angularjs-scope

经过一番研究,我无法找到问题的答案。

我有一个从数据库获取数据的 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 ...
            });    
        }
    };
});

Working Plunk

您可以了解有关$watch函数的更多信息here .

关于angularjs - 如何在指令中使用/同步 Controller 的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29496268/

相关文章:

php - 使用 Angular ngRepeat 显示 php 选择的 JSON 数据

angularjs - 如何在angularjs(ng-show)中应用更改?

node.js - 为什么在 ES6 模块中导出的对象有未定义的方法?

javascript - “Users\\PhpstormProjects\\easy-essay\\.babelrc 中指定的未知插件 "transform-runtime"

javascript - Mongoose "this.model is not a function"

javascript - 如何使用angular js将表格行添加为模板

javascript - 带 ionic 的单张 splinter 瓷砖

javascript - 使用 ng Repeat (Angular js) 在表中放置以逗号分隔的文本字段值

angularjs - 在两个数组上进行 ng-repeat

javascript - 指令 Angular 中的指令