来自指令控制器内的服务的Http调用

时间:2016-04-08 08:05:41

标签: javascript angularjs highcharts

我正在构建一个Angular指令来加载从中传递一些变量的Highchart.js区域图。

我正在使用像这样的指令

<andamento-fondo-area-chart color="#3FAE2A" url="../data.json"></andamento-fondo-area-chart>

我正在尝试使用指令本身的json数据传递url,通过服务进行http调用,然后使用指令内部的数据来构建图形。

下面你可以看到我为服务和指令编写的代码。 在指令控制器中,在服务调用之后,我将$ scope发送到控制台,然后发送$ scope.data。

我不理解的是当我输出$ scope时,我在其中有数据数组,填充了我的数据。在下一行输出$ scope.data本身,它给了我“undefined”。

see image to see my console output

你知道为什么吗?

 //Service
    OLS.service('dataService', function($http) {
        delete $http.defaults.headers.common['X-Requested-With'];
        this.getData = function(url) {
            return $http({
                url: url
            });
        }
    });

//Graph Directive using Highchart

OLS.directive('andamentoFondoAreaChart', function($http, dataService){
    return {
        restrict: 'E',
        template: '<div id="areaGraphContainer" style="width:100%;"></div>',
        scope: {
            url: '@',
            color: '@'
        },
        controller: function($scope){       
            dataService.getData($scope.url).then(function(dataResponse) {
                $scope.data = dataResponse;
            }); 
            console.log($scope);
            console.log($scope.data);           
        },
        link: function (scope, element, attrs) {        
            Highcharts.chart('areaGraphContainer', {
                chart: {
                    type: 'area',
                    ...
                },
                title.: {
                    ...
                },
                ...,
                series: [{
                    color: scope.color,
                    ...,
                    data: scope.data
                }]
            });
        }
    };  
});

1 个答案:

答案 0 :(得分:0)

看这里:

dataService.getData($scope.url).then(function(dataResponse) {
            $scope.data = dataResponse;
        }); 
console.log($scope);
console.log($scope.data);           

当你尝试打印$ scope.data时,$ scope没有,因为dataService没有完成请求,尝试访问里面的$ scope.data .then:

dataService.getData($scope.url).then(function(dataResponse) {
            $scope.data = dataResponse;
            console.log($scope.data); 
        }); 

<强>更新

也许用$ watch尝试这个?

link: function (scope, element, attrs) {  
      scope.$watch('data', function(newVal) {
        if(newVal) { Highcharts.chart('areaGraphContainer', ...);}
    }, true);      
相关问题