0

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
        }]
    }];



});

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Can you make a fiddle for this. when i does this its not working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.