微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJS三阶嵌套表结构

我有以下数据结构
{
    '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完成.

如果你真的,真的需要用rowpans这样做,这是一种方法,它是超级棘手的,几乎不可能阅读/遵循,除非你是作者(抱歉),但它的工作原理.你只需要几个$过滤器的支持

喜欢这个:

angular.module('testApp',[])
.controller('testController',function ($scope) {
    $scope.testData = {
        'Key 1': {
            'Value 1': ['a','e']
        },'Key 2': {
            'Value 3': ['f'],'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,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

原文地址:https://www.jb51.cc/angularjs/143341.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐