由于angular ng-repeat只能写在标签上 循环对象的对象时遇到的问题及解决方法

    对象数据结构

$scope.obj = {
    "section1":{
        "category1":{
            "key1":"value1",
            "key2":"value2"
        },
        "category2":{
            "key1":"value3",
            "key2":"value4"
        }
    },
    "section2":{
        "category3":{
            "key1":"value5",
            "key2":"value6"
        }
    }
    ...
};

    

    ng-repeat循环时的结构

<ul ng-repeat="(key,value) in obj">
    <li ng-repeat="(subkey,subValue) in value" >
        {{key}}
        {{subkey}}
        {{subValue.key1}}
        {{subValue.key2}}            
    </li>
</ul>

    

    这样循环输出的结果

<ul>
    <li>
        section1
        category1
        value1
        value2
    </li>
    <li>
        section1
        category2
        value3
        value4
    </li>
</ul>
<ul>
    <li>
        section2
        category3
        value5
        value6
    </li>
</ul>


而我希望的结果是li在一个ul中循环,这样可以避免当li的个数为奇数时,产生的布局问题。


最后解决的方法是改造对象,将它生成为一个新的数组进行循环。

$scope.buildData = function(){
    var newArr = [];
    angular.forEach($scope.obj,function(value,key){
         angular.forEach(value,function(subvalue,subkey){
             newArr.push({
                 "section": key,
                 "category": subkey,
                 "key1":subvalue["key1"],
                 "key2":subvalue["key2"]
             }) 
         });
    });
    return newArr;
};
$scope.newObj =  $scope.buildData();

//新的循环方法
<ul>
    <li ng-repeat="data in newObj ">
        {{data.section}}
        {{data.category}}
        {{data.key1}}
        {{data.key2}}
    </li>
</ul>


你可能感兴趣的:(Angular,elements,ng-repeat,Without)