I've been using the ngTableDynamic
directive recently and it works great when I know exactly what columns my table should expect. However, I'm running into issues when my table is truly dynamic and I do not know in advance the number or type of columns to expect.
At the top of my controller I declare the columns I know will be present in every table:
$scope.columns = [
{ title: 'ID', field: 'id', visible: true, required: true },
{ title: 'Email', field: 'email', visible: true, required: true }
];
I then make an asynchronous call to a service which returns results. Based on these results I push any additional column objects into $scope.columns
:
var getResults = function() {
var defer = $q.defer();
reportService.getReportResults({
report: $scope.id,
version: $scope.version
}).$promise.then(function(data) {
$scope.data = data.results;
_.each($scope.data[0], function(value, key) {
if (key !== 'id' && key !== 'email') {
$scope.columns.push({
title: _str.capitalize(key),
field: key,
visible: true,
required: false
});
}
});
defer.resolve($scope.data);
});
return defer.promise;
};
However, the columns pushed within _.each
never make it to my table when I view it in the browser. If I replace my asynchronous call with a hard-coded mock of an example set of data however, the columns are added and everything works as expected:
var getResults = function() {
var defer = $q.defer();
$scope.data = [{"id":"1","email":"test@sample.com",,"create_date":"2013-09-03T09:00:00.000Z"},{"id":"2","email":"sample@test.org","create_date":"2013-09-03T11:10:00.000Z"}];
_.each($scope.data[0], function(value, key) {
if (key !== 'id' && key !== 'email') {
$scope.columns.push({
title: _str.capitalize(key),
field: key,
visible: true,
required: false
});
}
});
defer.resolve($scope.data);
return defer.promise;
};
Further down in my controller my init code calls
getResults().then(function() {
$scope.tableParams.reload();
});
$scope.tableParams = new ngTableParams({...
My assumption is that as soon as the promise is resolved $scope.tableParams.reload();
is called before $scope.columns
is updated.