2017-04-27 80 views
-1
config.previewData = [ 
    { 
     Cartridges:27989, 
     Total Accounts:294, 
     Metrices:"MVC", 
     Toner Cartridges:5928, 
     INK Cartridges:22061 
    }, 
    { 
     Cartridges:56511, 
     Total Accounts:376, 
     Metrices:"SMB", 
     Toner Cartridges:15253, 
     INK Cartridges:41258 
    }, 
    { 
     Cartridges:84,500, 
     Total Accounts:670, 
     Metrices:"Grand Total", 
     Toner Cartridges:21,181, 
     INK Cartridges:63,319 
    }, 
] 

和我的HTML代碼,這樣從行移調動態表列,反之亦然

<table class="table table-striped"> 
    <thead> 
     <tr role="row"> 
      <th data-ng-repeat="(key, val) in config.previewData[0]"> 
       {{ key}} 
      </th> 
     </tr> 
    </thead> 

    <tbody> 
     <tr data-ng-repeat="row in config.previewData"> 
      <td data-ng-repeat="column in row"> 
       {{column}} 
      </td> 
     </tr> 
    </tbody> 
</table> 

這段代碼將打印完美的像下面的圖片 enter image description here

現在我要轉這個表成行到列和列到行。 這是可能的動態表,因爲我的對象是動態的不固定的。

幫助我,如果有人知道如何做到這一點。 轉表後看起來像這樣 enter image description here

回答

2

使用與您的示例代碼相同的假設(即config.previewData總是包含至少一個對象,所有對象具有相同的屬性...)

<table class="table table-striped"> 
    <tbody> 
     <tr data-ng-repeat="(key, val) in config.previewData[0]"> 
      <th> 
       {{ key }} 
      </th> 
      <td data-ng-repeat="row in config.previewData"> 
       {{ row[key] }} 
      </td> 
     </tr> 
    </tbody> 
</table> 
+0

非常感謝你 – Dixit

0

使用reduce,你可以有這樣的事情來轉您的數據,然後可以使用使用ng-repeat很容易遍歷!

例摘要(純JS爲了簡化):

var previewData = [{ 
 
    "Cartridges": 27989, 
 
    "Total Accounts": 294, 
 
    "Metrices": "MVC", 
 
    "Toner Cartridges": 5928, 
 
    "INK Cartridges": 22061 
 
    }, 
 
    { 
 
    "Cartridges": 56511, 
 
    "Total Accounts": 376, 
 
    "Metrices": "SMB", 
 
    "Toner Cartridges": 15253, 
 
    "INK Cartridges": 41258 
 
    }, 
 
    { 
 
    "Cartridges": 84500, 
 
    "Total Accounts": 670, 
 
    "Metrices": "Grand Total", 
 
    "Toner Cartridges": 21181, 
 
    "INK Cartridges": 63319 
 
    } 
 
] 
 

 
var transpose = previewData.reduce(function(arr, obj) { 
 
    for (let key in obj) { 
 
    if (obj.hasOwnProperty(key)) { 
 
     arr[key] = arr[key] || [] 
 
     arr[key].push(obj[key]) 
 
    } 
 
    } 
 
    return arr 
 
}, {}) 
 

 
console.log(transpose)

+0

,這不是單純angularjs代碼 – Dixit

+0

@ dkc007只是範圍內的變量替換正常的變量。純粹的JS只是爲了簡單起見 – tanmay

0

這是唯一的(髒),這樣我可以想出來

<tr> 
     <td data-ng-repeat="row in previewData">{{row['Metrices']}}</td> 
    </tr> 
    <tr> 
     <td data-ng-repeat="row in previewData">{{row['Total Accounts']}}</td> 
    </tr> 
    <tr> 
     <td data-ng-repeat="row in previewData">{{row['Toner Cartridges']}}</td> 
    </tr> 

.... ..等等

其他選項:Transposing JSON