使用angularJS将动态列绑定到表 [英] Bind dynamic columns to a table using angularJS

查看:65
本文介绍了使用angularJS将动态列绑定到表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从外部服务中获取一些数据,并且试图将其显示在表上.问题是我从服务获得的数据将包含动态列,有时会有5列,而其他时候则是8.我不知道如何在ng-repeat中处理它.并使用 ng-grid 之类的东西并不是一个好的解决方案将仅显示10行.为此,如果我使用任何外部解决方案都将产生开销.有没有角度方法可以做到这一点?如果不是这样的话,什么是最好的选择.

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.

$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.在表头上使用中继器(如果对象可以具有不同的属性,则需要查找具有最多属性/列数的对象)

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

3.在表格单元格上使用中继器

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

这篇关于使用angularJS将动态列绑定到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆