我试图动态地将FusionCharts添加到AngularJS页面中。我正在将图表数据加载到模型对象中,该图表对象会显示,但是内容为“无数据可显示”。

我的app.js:

(function () {

var modelListOfCharts = ["1", "4", "5", "6"];
var model = {};
var app = angular.module('chartDash', ["ng-fusioncharts"]);

app.controller('fussionController',["$scope","DataService", function ($scope, DataService) {
    $scope.chartData = {};

    DataService.getThings().then(function () {
        $scope.myListOfCharts = modelListOfCharts;
        $scope.chartData = model;
    });
}]);

app.service("DataService", ["$http", "$timeout", "$q", function ($http, $timeout, $q) {
    return {
        getThings: function () {
            var dfd = $q.defer();
            $timeout(function () {
                angular.forEach(modelListOfCharts, function(chartId) {
                    $http.get('/FusionCharts/GetChartData/', { params: { chartID: chartId } }).success(function (result) {
                        model[chartId] = result;
                    });
                });
                dfd.resolve(model);
            }, 300);
            return dfd.promise;
        }
    };
}]);
})();


我的html:

<div ng-controller="fussionController">
    <div ng-repeat="n in myListOfCharts">
        <h2>Chart number {{n}}</h2>
        <fusioncharts width="100%"
                      height="400"
                      type="MSCombi2D"
                      datasource="{{chartData[n]}}"></fusioncharts>
    </div>
</div>


当我把dfd.resolve(model);在循环内可以正常工作,但只显示一张图表的数据。

    app.service("DataService", ["$http", "$timeout", "$q", function ($http, $timeout, $q) {
    return {
        getThings: function () {
            var dfd = $q.defer();
            $timeout(function () {
                angular.forEach(modelListOfCharts, function(chartId) {
                    $http.get('/FusionCharts/GetChartData/', { params: { chartID: chartId } }).success(function (result) {
                        model[chartId] = result;
                        dfd.resolve(model);
                    });
                });

            }, 300);
            return dfd.promise;
        }
    };
}]);

最佳答案

由于有多个http获取,因此会有多个承诺。因此,您必须等待所有这些承诺都得到解决。尝试这个。

app.service("DataService", ["$http", "$timeout", "$q", function ($http, $timeout, $q) {
    return {
        getThings: function () {
            var arrayOfPromises = [];
                angular.forEach(modelListOfCharts, function(chartId) {
                    arrayOfPromises.push($http.get('/FusionCharts/GetChartData/', { params: { chartID: chartId } }).success(function (result) {
                        model[chartId] = result;
                    }));
                 });

            return $q.all(arrayOfPromises);
        }
    };
}]);

关于javascript - 为什么不在循环中时, promise 不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30600687/

10-09 14:25