I am using Angularjs and c3 charts directives. My template compilation code is
angular.element(document.body).append($compile(template)($scope));
I want this template compilation code to be executed only after all the promises inside the for loop are completed. Can any one help me how can I achieve it? And also for dynamically assigning model names I have used $scope[data.chartIdent], is it right way? The following is the sample code of my controller.
var chartTabs = [
{
title:' Spend',
pages:[
{
chart_Id:0,
chart_name:"C0",
chart_type:"line",
chart_call_name:"spendAmount"
},
{
chart_Id:1,
chart_name:"C1",
chart_type:"bar"
chart_call_name:"spendItems"
}
]
}
];
var chartArray = chartTabs .pages;
var template = '<div class= "chartsDiv">';
for(var i = 0; i < chartArray .length; i++) {
var eachChart= chartArray [i];
var chartIdent = "chart" + i ;
var chartPromise = dataService.getDataForC3Chart(chart_call_name);
chartPromise .then(function (data) {
$scope[data.chartIdent] = {
data : {
x: 'x',
columns :data.columns,
type : data.chart_type
},
axis : {
x: {
type: 'timeseries',
tick: format: function(value) {
var month = value.getUTCMonth() + 1;
var year = value.getUTCFullYear();
return month + '-' + year;
}
}
},
subchart : {
show : true
}
};
}
}, function (error) {
$scope[data.chartIdent] = {};
alert(error);
});
template += ' <div class="col"> <p class="graphtitle">' + eachDashboard.chart_name + ' </p> <c3-simple id = "chart' + i + '" config="chart' + i + '" ></c3-simple> </div>';
}
template += ' </div>';
angular.element(document.body).append($compile(template)($scope));
using $q.all, how to formulate the template dynamically, here 'i' values are not avaialable for the template as we are out of for loop.
$scope.createDashboradsforeachTab = function(eachTab) {
var dashboardslayoutArray = eachTab.pages;
var promises = [];
var template = '<div class= "chartsDiv">';
for(var i = 0; i < dashboardslayoutArray.length; i++) {
var eachChart= chartArray [i];
var chartIdent = "chart" + i ;
var chartPromise = dataService.getDataForC3Chart(chart_call_name);
var chartPromise = dataService.getDataForC3Chart(chart_call_name);
promises.push(chartPromise);
}
$q.all(promises)
.then(function(data){
// all promises were resolved here
$scope[data.chartIdent] = {
data : {
x: 'x',
columns :data.columns,
type : data.chart_type
}
};
},function(error) {
$scope[data.chartIdent] ={};
alert(error);
}
);
template += ' <div class="col"> <p class="graphtitle">' + eachDashboard.chart_name + ' </p> <c3-simple id = "chart' + i + '" config="chart' + i + '" ></c3-simple> </div>';
template += ' </div>';
angular.element(document.body).append($compile(template)($scope));
}
You need to collect all the promises into an array and use
$q.all
:Off Topic: please read more about Angular so that you won't do things like:
angular.element(document.body).append($compile(template)($scope));