aliaz aliaz - 9 days ago 6
AngularJS Question

Angularjs - formatting a table with ng-repeat where a column does not have any data

I have a table as shown in the plunkr example.

https://plnkr.co/edit/8KK9JdlBqOYX78ywmLYN?p=preview

In this case, no data exists for 'east' or 'west' in $scope.siteData in the controller, but for 'north', 'south' and 'central'.

The data for 'central' is showing under 'east'

How do I display empty column under 'east' and 'west' when ng-repeat does not have any data.

Here is my html

<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th >Month</th>
<th >North</th>
<th >South</th>
<th >East</th>
<th >West</th>
<th >Central</th>
<th >Total</th>
</tr>
</thead>
<tbody ng-repeat="items in siteData" >
<tr >
<td>
{{items.monthYear | date:'MMMM - yyyy' }}
</td>
<td ng-repeat="region in items.regions | filter: {regionName: 'North'}">
{{region.capacity.allocated }} / {{region.capacity.capacity}}
</td>
<td ng-repeat="region in items.regions | filter: {regionName: 'South'}">
{{region.capacity.allocated }} / {{region.capacity.capacity}}
</td>
<td ng-repeat="region in items.regions | filter: {regionName: 'East'}">
{{region.capacity.allocated }} / {{region.capacity.capacity}}
</td>
<td ng-repeat="region in items.regions | filter: {regionName: 'West'}">
{{region.capacity.allocated}} / {{region.capacity.capacity}}
</td>
<td ng-repeat="region in items.regions | filter: {regionName: 'Central'}">
{{region.capacity.allocated}} / {{region.capacity.capacity}}
</td>
</tr>
</tbody>
</table>
</div>
</div>


Sorry about the vague title and description. I'm not so good with words.

Answer

I expect it would be more efficient to use a filter function than a lot of ngRepeats.

You can add a data matching function to the controller:

$scope.findData = function(data, filter) {

    record = data.regions.filter(function(v, i){
        if(v.regionName === filter) return true;
    }); // returns an array of matches

    // get first item in array if exists else return empty string
    return (record.length > 0) ? record[0].capacity.allocated + ' / ' + record[0].capacity.capacity : '';
};

And then replace your HTML with:

<td>
   {{ findData(items, 'North') }}
</td>
<td>
   {{ findData(items, 'South') }}
</td>
<td>
   {{ findData(items, 'East') }}
</td>
<td>
   {{ findData(items, 'West') }}
</td>
<td>
   {{ findData(items, 'Central') }}
</td>

Example: https://plnkr.co/edit/qZsIQKSwUwf4UEud5wxc?p=preview