[英]Flexible table ng-repeat
是否可以進行以下操作,如果可以,如何更改HTML以允許它?
我有以下模型;
prospect = [{"name":"jamie",
"phones": [{
"type":"home",
"number":"01275"},
{
"type":"mobile",
"number":"0788"}]},
{"name":"peter",
"phones": [{
"type":"mobile",
"number":"07852"}]}
]
我想在angularjs表中顯示這樣
name home mobile
jamie 01275 0788
peter 07852
我目前的HTML
<table>
<tbody ng-repeat='person in prospect'>
<th>Name</th>
<th ng-repeat="phone in person.phones">{{phone.type}}</th>
<tr>
<td>
{{person.name}}
</td>
<td ng-repeat='phone in person.phones'>
{{phone.number}}
</td>
</tr>
</tbody>
</table>
產生
Name home mobile
jamie 01275 0788
Name mobile
peter 07852
要在html中完成此操作,而不修改您的json,我首先添加一個數組,該數組指示每種類型的電話進入以下各列:
$scope.types= ["home","mobile"];
然后在標題中使用它:
<th ng-repeat="type in types">{{type}}</th>
然后,要打印出電話號碼,我們將在ngIf
中有條件地顯示與該列類型匹配的所有電話,以遍歷每一列中的每個電話:
<td ng-repeat='type in types'>
<span ng-repeat='pphone in person.phones' ng-if="pphone.type == type">
{{pphone.number}}
</span>
</td>
一種變體是用自定義指令替換嵌套的ngRepeat
,該指令顯示給定列和行的正確電話。
我希望你會喜歡這個解決方案:)
我對你有這種依賴性
bower install angular
bower install ng-tasty
bower install bootstrap
這是完整的解決方案
<div tasty-table bind-resource="resource">
<table class="table table-striped table-condensed">
<thead tasty-thead></thead>
<tbody>
<tr ng-repeat="row in rows">
<td ng-bind="row.name"></td>
<td ng-bind="row.phones | filterTypeColumn:'home'"></td>
<td ng-bind="row.phones | filterTypeColumn:'mobile'"></td>
</tr>
</tbody>
</table>
</div>
<script src="bower_components/angular/angular.min.js"></script>
<script src="bower_components/ng-tasty/ng-tasty-tpls.min.js"></script>
<script>
angular.module('stackOverflowAnswer', ['ngTasty'])
.filter('filterTypeColumn', function() {
return function (input, typeColumn) {
var phoneNumber;
input.forEach(function (phone) {
if (phone.type === typeColumn) {
phoneNumber = phone.number;
}
})
return phoneNumber;
};
})
.controller('StackOverflowController', function ($scope) {
$scope.resource = {
"header": [
{ "name": "Name" },
{ "home": "Home" },
{ "mobile": "Mobile" }
],
"rows": [
{
"name":"jamie",
"phones": [
{ "type":"home","number":"01275" },
{ "type":"mobile", "number":"0788"}
]
},
{
"name":"peter",
"phones": [
{ "type":"mobile","number":"07852"}
]
}
]
};
});
</script>
</body>
</html>
如果您想了解有關ngTasty的更多信息,可以在http://zizzamia.com/ng-tasty/directive/table上找到所有文檔。 對於您的特定情況,解決方案是創建自定義過濾器。
再見
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.