I'm binding JSON data to ng-table
using Angular.js.
If any value is null then positions for all columns gets disturb. How can I fix the data with column header?
See this Plunker: http://plnkr.co/edit/Ixvp8B0dRwOBDHflmu2j?p=preview
Description
should be null
but all values shifted to left.
Or, if all values are null for any property hide that particular column.
In order to determine if a column is empty you need some sort of column configuration that gets created by iterating the data to see if all rows contain data for any of the headings (object keys).
Then you can use that column configuration array as the repeater for the <th>
and <td>
.
Example config:
[
{
"heading": "Id",
"display": true
},
{
"heading": "Title",
"display": true
},
{
"heading": "Description",
"display": true
},
{
"heading": "Test",
"display": false
}
]
HTML
<thead>
<tr>
<th ng-repeat="col in colConfig" ng-if="col.display">{{col.heading}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in data">
<td ng-repeat="col in colConfig" ng-if="col.display">
{{item[col.heading]}}
</td>
</tr>
</tbody>
Example config create
var keys = Object.keys(data[0]);
function createConfig() {
var validKeyCounts = {};
var colConfig;
keys.forEach(function (key) {
validKeyCounts[key] = 0;
})
data.forEach(function (row, idx) {
keys.forEach(function (key) {
if (row.hasOwnProperty(key) && row[key] !== null) {
validKeyCounts[key]++;
}
})
});
colConfig = keys.map(function (key) {
return {
heading: key,
display: validKeyCounts[key] > 0
}
});
return colConfig
}
I'm sure this could be optimized but is just a way to get started with functionality wanted