我的要求是显示条形图。我正在使用 angularjs 和 Zingchart 来显示条形图。下面是调用生成栏的 javascript 代码。我在下面提到的代码中迭代逻辑(angular.forEach ..)时遇到问题。
我在 angular.forEach 中的警报语句显示了 3 次,但在 UI 上我只能看到一个条显示(即显示带有最终数据的条,前两个条未显示)。 我知道我遗漏了绘制每个条形图而不是最后显示的条形图的东西。我需要使用任何推送状态吗?请指教。
app.controller('myController',['$rootScope','$scope','$uibModal','myService',function($rootScope,$scope,$uibModal,myService) {
$scope.chart = {};
$scope.chart.options = {
"isStacked": "true",
axisFontSize : 10,
chartArea: {left:0, width: 400,}
};
$scope.chart.type = "bar";
$scope.chart.cssStyle = "height:300px; width:650px;";
$scope.loadChartData = function(){
alert("Chart data loading");
MyService.getChartData($rootScope.myID).then(
function(response) {
$scope.myJson=response;
angular.forEach($scope.myJson,function(value,key){
alert("in foreach"); //displaying 3 times
sub = value.myResults.sub;
spread = value.myResults.spread;
active =value.myResults.active;
$scope.data = {};
$scope.data.valuesOne = [sub];
$scope.data.valuesTwo = [spread];
$scope.data.valuesThree = [active];
$scope.aValues = [$scope.data.valuesOne,$scope.data.valuesTwo,$scope.data.valuesThree];
$scope.myJson = {
type : "bar",
"background-color": "white",
"plot": {
"stacked": true,
"stack-type":"normal"
},
title:{
backgroundColor : "transparent",
fontColor :"black",
text : "Hello world"
},
backgroundColor : "white",
series : [
{
backgroundColor : '#00baf2'
},
{
backgroundColor : '#4caf4f'
}
]
};
});
},
function(errResponse){
console.error('Error while data retrieval');
});
}
}]);
html代码:
<div ng-controller="myController">
<div zingchart id="chart-2" zc-json="myJson" zc-width="700px" zc-height="568px" zc-values="aValues"></div>
</div>
使用上面提到的 js 代码,我应该在 UI 上看到 3 个栏,我只能查看一个栏。请建议。
最佳答案
您需要对数据而不是整个图表调用 foreach。像这样:
...
function(response) {
$scope.myJson = {
type: "bar",
"background-color": "white",
"plot": {
"stacked": true,
"stack-type": "normal"
},
title: {
backgroundColor: "transparent",
fontColor: "black",
text: "Hello world"
},
backgroundColor: "white",
series: [
{
backgroundColor: '#00baf2'
},
{
backgroundColor: '#4caf4f'
}
]
};
var subs = []
var spreads = []
var actives = []
$scope.aValues = [subs, spreads, actives]
angular.forEach(response, function (value, key) {
subs.push(value.myResults.sub)
spreads.push(value.myResults.spreads)
actives.push(value.myResults.active)
});
},
function(errResponse) {
console.error('Error while data retrieval');
});
...
关于javascript - 在 js 文件中使用 forEach 逻辑时无法按预期查看输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43098043/