我正在使用 Angularjs 和 c3 图表指令。我的模板编译代码是
angular.element(document.body).append($compile(template)($scope));
我希望这个模板编译代码只有在 for 循环内的所有承诺都完成后才能执行。任何人都可以帮助我如何实现它?而且对于动态分配模型名称,我使用了 $scope[data.chartIdent],这是正确的方法吗?以下是我的控制器的示例代码。
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));
使用 $q.all,如何动态地制定模板,这里的 'i' 值不适用于模板,因为我们不在 for 循环中。
$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));
}