gpt4 book ai didi

AngularJS 三阶嵌套表结构

转载 作者:行者123 更新时间:2023-12-03 07:56:26 25 4
gpt4 key购买 nike

假设我有以下数据结构

{
'Key 1': {
'Value 1': ['a', 'b', 'c'],
'Value 2': ['d', 'e']
},
'Key 2': {
'Value 3': ['f'],
'Value 4': ['g', 'h']
}
}

如何使用 AngularJS 将其呈现在类似于以下的表格中:

|-------|---------|---|
| Key 1 | Value 1 | a |
| | |---|
| | | b |
| | |---|
| | | c |
| |---------|---|
| | Value 2 | d |
| | |---|
| | | e |
|-------|---------|---|
| Key 2 | Value 3 | f |
| |---------|---|
| | Value 4 | g |
| | |---|
| | | h |
|-------|---------|---|

键是通过 rowspan 完成的。

最佳答案

如果你真的,真的需要用 rowspan 来做这件事,这是一种方法,除非你是作者,否则它非常棘手,几乎不可能阅读/遵循(抱歉) ,但它有效。你只需要几个 $filters

的支持

像这样:

angular.module('testApp', [])
.controller('testController', function ($scope) {
$scope.testData = {
'Key 1': {
'Value 1': ['a', 'b', 'c'],
'Value 2': ['d', 'e']
},
'Key 2': {
'Value 3': ['f'],
'Value 4': ['g', 'h']
}
};
})
.filter('nNestedElements', function(){
var nNestedElements = function(collection, currentLevel, stopLevel){
var total = 0;
if(stopLevel==currentLevel){
if(Object.prototype.toString.call(collection) === '[object Array]')
total += collection.length;
else
total += Object.keys(collection);
}else{
angular.forEach(collection, function(value){
total += nNestedElements(value, currentLevel+1, stopLevel);
});
}
return total;
};
return function(object, level){
return nNestedElements(object, 0, level);
}
})
.filter('objectKeys', function(){
return function(object){
return Object.keys(object);
};
});

查看:

<table ng-app="testApp" ng-controller="testController">
<tr ng-repeat-start="(key, val) in testData">
<td rowspan="{{val|nNestedElements:1}}">{{key}}</td>
<td rowspan="{{val[(val|objectKeys)[0]].length}}">{{(val|objectKeys)[0]}}</td>
<td>{{ val[(val|objectKeys)[0]][0]}}</td>
</tr>
<tr ng-repeat="val2 in val[(val|objectKeys)[0]].slice(1)">
<td>{{val2}}</td>
</tr>
<tr ng-repeat-start="subkey in (val|objectKeys).slice(1)">
<td rowspan="{{val[subkey].length}}">{{subkey}}</td>
<td>{{ val[subkey][0] }}</td>
</tr>
<tr ng-repeat="value3 in val[subkey].slice(1)" ng-repeat-end>
<td>{{ value3 }}</td>
</tr>
<tr ng-repeat-end ng-if="false" ><td></td></tr>
</table>

Example

关于AngularJS 三阶嵌套表结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26566520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com