如何全局访问成功数据。我已全局声明barChartData
并将成功数据值设置为barChartData
。但我无法在dataSource: barChartData,
中获取
var app = angular.module("anglesExample", []);
var barChartData;
app.controller('CitiesCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'POST',
url: 'getReport.php'
}).
success(function (data, status, headers, config) {
barChartData = data.collectionSummery;
}).
error(function (data, status, headers, config) {
});
}]);
$(window).load(function () {
$("#chartContainer").dxChart({
dataSource: barChartData,
series: {
argumentField: 'DIVISIONS',
valueField: 'SUMMERY',
name: "Collection Summery",
type: "bar",
color: '#ffa500',
label: {
visible: true,
connector: {
visible: true
}
}
},
tooltip: {
enabled: true,
percentPrecision: 2,
customizeText: function (value) {
return value.percentText;
}
},
legend: {
horizontalAlignment: 'center',
verticalAlignment: 'bottom'
}
});
});
我该如何解决?我需要$ q承诺吗?
答案 0 :(得分:2)
问题似乎是ajax的异步行为。实际上你的代码说当ajax调用完成时放入dxchart,但你的页面加载在ajax调用之前完成,所以你在全局变量barChartData
中没有任何东西。
您可以尝试以函数方式执行:
var app = angular.module("anglesExample", []);
app.controller('CitiesCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'POST',
url: 'getReport.php'
}).
success(function (data, status, headers, config) {
makeChart(data.collectionSummery); // pass the data in the func
}).
error(function (data, status, headers, config) {
// error stuff
});
}]);
function makeChart (data) { // set the data in the args
$("#chartContainer").dxChart({
dataSource: data, // use the passed data
//all the stuff of dxchart
});
}
您可以创建全局函数并将所需数据作为参数传递。