简体   繁体   中英

Bind dynamic columns to a table using angularJS

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



});

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM