Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am getting some data from an external service and I am trying to show it on a table. The problem is that the data I get from service will be with dynamic columns, some times there will be 5 column another time 8. I don't know how I could handle it in ng-repeat. and using things like ng-grid won't be a good solution I think as there will be only 10 rows to display. for this If I use any external solution that will be a overhead. Is there any angular method to achieve this? if not what is the best option for this small data.

Note: Column names will also be dynamic My code

<div ng-app='myApp' ng-controller="MainCtrl">
<div ng-repeat="prdElement in packageElement track by $index" class="package-grid">
    <table class="hovertable">
        <thead>
            <tr>
                <th>Line #</th>
                <th>Quantity in Plt</th>
                <th>Allready Packed</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="data in prdElement.Data" ng-init="data.newquantity  = 0">
                <td>{{data.itemId}}</td>
                <td>
                    {{data.quantity}}
                </td>
                <td>{{data.packed}}</td>
            </tr>
        </tbody>
    </table>
</div>

angular.module('myApp', []).controller('MainCtrl', function ($scope) {
    var counter = 0;
    $scope.packageElement = [{
        name: counter,
        show: true,
        Data: [{
            name: 'item 1',
            itemId: '284307',
            quantity: '100',
            packed: 0

        }, {
            name: 'item 2',
            itemId: '284308',
            quantity: '200',
            packed: 0
        }]
    }];



});
share|improve this question

1 Answer 1

up vote 1 down vote accepted

Will there be the same number of columns for all data items? If so, I think you can do this.

1. Define a function on your scope that gives you the object keys:

$scope.keys = function(obj) {
    var key;
    var keys = [];
    for (key in obj) {
        if (key === "$$hashKey") break; //angular adds new keys to the object
        if (obj.hasOwnProperty(key)) keys.push(key);
    }
    return keys;
  }

2. use a repeater on the table header (if the objects can have different properties, you need to find the object with the highest number of properties/columns)

<th ng-repeat="key in keys( prdElement.Data[0] )">{{key}}</th>

3. use a repeater on the table cell

<td ng-repeat="key in keys( prdElement.Data[0] )">{{ data[key] }}</td>
share|improve this answer
    
Can you make a fiddle for this. when i does this its not working –  Athul Oct 15 at 10:37
    

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.