2014-04-05 19 views
2

從Web服務中,我得到一個JSON字符串。它可能會根據請求而有所不同。 2 JSON結果被在AngularJS中顯示動態JSON

結果1

[ 
    { 
    "Key": 1, 
    "ID": 1, 
    "applicationId": "1", 
    "applicationName": "APP1" 
    }, 
    { 
    "Key": 2, 
    "ID": 1, 
    "applicationId": "2", 
    "applicationName": "APP2" 
    } 
] 

結果2

[ 
    { 
    "OrgKey": 1, 
    "ID": 1, 
    "OrgID": "1", 
    "OrgName": "Org1" 
    }, 
    { 
    "OrgKey": 2, 
    "ID": 4, 
    "OrgID": "6", 
    "OrgName": "Org2" 
    } 
] 

如何將我的表格中顯示這個?

在控制器JS文件我用的是$http.get方法和成功的方法,我把

$scope.resultData = data; 

但在HTML我怎麼會顯示動態內容?

<table> 
<thead> 
    <tr> 
    <th ng-repeat = "result in resultData"> 
    <!-- Not the right way --> 
    <!-- Here I want to put the headers like "Key,ID" ... --> 
    </th> 
    </tr> </thead> 
    <tbody> 
    <tr ng-repeat = ""result in resultData"> 
    <td> {{result.Key }} </td> 
    <!-- When the firlds vary, how to put? -> 
    </tr> 
    </tbody> 
</table> 

可能嗎?如果是這樣如何?謝謝。

+0

看到這個答案,它可以幫助你:http://stackoverflow.com/questions/18357370/angularjs-building-a-dynamic-table- based on a-json/18357643#18357643 –

+0

基於http://docs.angularjs.org/api/ng/service/$http,請確保以正確的方式實現'$ http.get'(異步調用)。否則,HTML將不顯示任何內容。 –

+0

但是那裏的JSON格式是一樣的。 – iCode

回答

10

首先你應該得到第一行設置你的表格標題中這樣

<thead> 
    <tr> 
    <th ng-repeat="(header, value) in resultData[0]"> 
     {{header}} 
    </th> 
    </tr> 
</thead> 
後,這對您的 tbody你應該把你排第一則行行程內的所有細胞

<tbody> 
    <tr ng-repeat="row in resultData"> 
    <td ng-repeat="cell in row"> 
     {{cell}} 
    </td> 
    </tr> 
</tbody> 

這裏工作PLUNKER ...

UPDATE

一些用戶問是否可以這樣處理不排序頭和它們的值...

的答案是肯定的開始你應該知道爲什麼它已經alphabetacally排序前...

ng-repeat指令工作differentlly用數組和對象......如果你使用數組你可以把它排序,但是這不是對象的選擇在這裏是一個discussion它...

所以現在最好的辦法是推對象值變成a rray我們使用他們的NG-重複之前..

這裏是第二PlUNKER

注意:您將看到我從數組中刪除$$ hashKey,因爲它們不是原始元素的屬性,角添加它們自動進入對象以觀看更改

+0

嗨。我只是想知道這是否可以在沒有排序的情況下完成!現在表格標題正在按字母順序排序 – Abhishek

+1

@crozzfire [PLUNKER](http://plnkr.co/edit/p6E3IKf02LV2CP19MpzW?p=preview) –

+0

@crozzfire你可以查看更新部分了解更多信息... –

1

我能夠建立一個動態表格,關閉其他人的示例和文檔。 http://jsfiddle.net/lastlink/v7pszemn/1/

<tr> 
    <th class="{{header}}" ng-repeat="(header, value) in items[0]" ng-click="changeSorting(header)"> 
    {{header}} 
    <i ng-class="selectedCls2(header)"></i> 
</tr> 
<tbody> 
<tr ng-repeat="row in pagedItems[currentPage] | orderBy:sort.sortingOrder:sort.reverse"> 
    <td ng-repeat="cell in row"> 
      {{cell}} 
    </td> 
</tr> 

雖然列失靈,在我的.NET項目,他們是爲了。

0

也許這不是最好的解決方案,但它確實爲我工作。在我的 當前項目im使用webSocket流數據,並需要動態顯示它在ui中,只要我從服務器獲取數據。

因此該解決方案是很簡單,做了什麼,我想......

在$超時結束了功能。

vm.testErrors = []; 
 

 
socket.onmessage(function(event) {  
 
    if (event.data !== 'connected') { 
 
    $timeout(function() { 
 
     addNewTestWithError(event.data); 
 
    }, 0); 
 
    } 
 
});
<div ng-repeat="item in vm.testErrors> 
 
    <h3>{{item.fullTitle}}</h3> 
 
    <h4>{{item.error}}</h4> 
 
</div>

希望它有助於