AngularJS + jQuery Flot + 通过控制器使用http.get加载数据

3

我已经设置了一个指令来处理在AngularJS中加载jQuery Flot图表:

var Dashboard = angular.module('StatsDashboard', []);

Dashboard.directive('chart', function() {
    return {
        restrict: 'E',
        template: '<div></div>',
        replace: true,
        link: function(scope, elem, attrs) {
            var chart = null;
            var data = scope[attrs.ngModel];
            var options = {}

            $.plot(elem, data, options);
            elem.show();
            }
        };
});

该指令从控制器中加载:
function ChartCtrl($scope, $http)
{
    $http.get('controllers/weekly_overview_charts.php').success(function(data) {
        $scope.reg_vs_act = data;
        });
}

我遇到了一个"TypeError: Cannot read property 'length' of undefined at parseData"的错误。

我确认了这是由于http函数的异步特性导致的。

我的问题是,我该如何确保数据在指令尝试加载flot图表之前被返回?

谢谢!


实际上,有很多关于flot指令的示例。我是基于此进行编写的:https://gist.github.com/jrmoran/3966529。您需要在数据上设置监视并确保在绘制图形之前数据有效。 - Karen Zilles
2个回答

0

回答我自己的问题:

scope.$watch(attrs.ngModel, function(v){
    if(v)
    {
        chart = $.plot(elem, v, options);
        elem.show();
    }
});

这个问题让 scope.$watch 函数出现了错误:

var data = scope[attrs.ngModel];

在这种情况下,应该简单地使用 attrs.ngModel。

0
我认为Erik的回答解决了这个问题,只是想补充一下显示的错误可能是因为$scope.reg_vs_act未定义。因此,为了解决错误并支持在数据可用之前初始化图表,您可以尝试使用以下代码:
function ChartCtrl($scope, $http)
{
    $scope.reg_vs_act = []; //Init to array with length 0
    $http.get('controllers/weekly_overview_charts.php').success(function(data) {
        angular.copy(data, $scope.reg_vs_act); //Assignment would also work with a watch, but you would loose the reference to the original array
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接