Kiran Kiran - 5 months ago 20
AngularJS Question

How to display json data in two columns in a table using angular

I have data in my json it will be dynamic and I want to display the data in a table with two columns. I am trying but only the first two records are repeating. I don't see all the records in the table.. Any help?

http://plnkr.co/edit/Hnb7hkjA16XDbzRT8VAt?p=preview

This is my json : var data = '{
"output":{
"service-status":[
{
"service":"db",
"service-name":"Mongo DB"
},
{
"service":"license",
"service-name":"Smart License"
},
{
"service":"BRM",
"service-name":"Billing"
},
{
"service":"subscription",
"service-name":"subscription"
}
]
}
}';


my html code:

<table border="1px" width="100%" ng-repeat="data in serviceData" ng-if="$index % 2 == 0">
<tr>
<td>{{serviceData[index]["service-name"]}}</td>
</tr>
</table>

i want to display something like this

Mongo Db Smart License
Billing subscription

Answer

Transform your data in the controller:

var serviceDataView = function() {
    var res = [];
    for (var i = 0; i < $scope.serviceData.length; i+=2){
      res.push({
        col1: $scope.serviceData[i]['service-name'], 
        col2: $scope.serviceData[i+1] ? $scope.serviceData[i+1]['service-name'] : null
      });
    }
    return res;
};

$scope.structuredData = serviceDataView();

So that it can be easily used in the view:

<table border="1px" width="100%">
    <tr ng-repeat="data in structuredData">
        <td>{{data.col1}}</td>
        <td>{{data.col2}}</td>
    </tr>
</table>

Plunker.