如何在AngularJS中显示动态表?

时间:2016-06-11 15:52:37

标签: angularjs json dynamic-tables

我试图创建一个动态表,根据JSON的制作方式,它会相应地加载所有数据。到目前为止,我有这个:

负责创建表格的HTML:

<div class="container" ng-controller="QuotationsController as vm">
<h2>Quotations</h2>
<p>
    <a href="\">Create Quotation</a>
</p>   
<table class="table">
    <tr ng-repeat="Quotation in vm.Quotations">
        <th ng-repeat="(key,val) in Quotation"> {{ key }} </th>             
    </tr>
    <tr ng-repeat="Quotation in vm.Quotations">
        <td ng-repeat="(key,val) in Quotation"> {{ val }}</td>
        <td>
            <a href="\">Edit</a> |
            <a href="\">Details</a> |
            <a href="\">Delete</a>
        </td>
    </tr>
</table>

控制器:

(function () {
"use strict";

angular
    .module("PPM")
    .controller("QuotationsController", ["QuotationsService", QuotationsController]);    

function QuotationsController(QuotationsService) {

    var vm = this;

    vm.Quotations = [
    {
        "ID": 1,
        "Description": "Leaf Rake",
        "Name": "GDN-0011",            
    },
    {
        "ID" : 2,
        "Description": "Garden Cart",
        "Name": "GDN-0023",            
    },
     {
         "ID": 5,
         "Description": "Hammer",
         "Name": "TBX-0048",             
     },
     {
         "ID": 8,
         "Description": "Saw",
         "Name": "TBX-0022",             
     },
     {
         "ID": 10,
         "Description": "Video Game Controller",
         "Name": "GMG-0042",             
     }
    ];        
}

})();

(我在控制器中对数据进行了硬编码,仅用于测试目的。稍后我会删除它并调用Web API。)

这给了我以下结果:

enter image description here

我不希望为每个存在的报价重复表标题。我只想展示一次,但我不知道如何在不使用ng-repeat的情况下获取属性。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您有多个标头,因为您在包含<tr>元素的<th>元素上使用了ng-repeat。删除ng-repeat。

<table class="table">
    <tr>
        <th ng-repeat="(key,val) in vm.Quotation[0]"> {{ key }} </th>             
    </tr>
    <tr ng-repeat="Quotation in vm.Quotations">
        <td ng-repeat="(key,val) in Quotation"> {{ val }}</td>
        <td>
            <a href="\">Edit</a> |
            <a href="\">Details</a> |
            <a href="\">Delete</a>
        </td>
    </tr>
</table>

这样的事情应该有用。

如果有0个元素,你可能想添加ng-if。

答案 1 :(得分:1)

让你的控制器循环完成第一个结果或让html做到这一点。无论哪种方式。

Html方式

    <div class="container" ng-controller="QuotationsController as vm">
<h2>Quotations</h2>
 <p> 
    <a href="\">Create Quotation</a>
 </p>
 <table class="table">
     <tr >
        <th ng-repeat="(key,val) in vm.Quotations[0] "> 
          {{ key }}
        </th> 
     </tr>
     <tr ng-repeat="Quotation in vm.Quotations"> 
        <td ng-repeat="(key,val) in Quotation">
           {{ val }}
        </td> 
        <td>
            <a href="\">Edit</a> | <a href="\">Details</a> | <a href="\">Delete</a> 
        </td> 
     </tr> 
</table>