嵌套循环Angular.JS使用复杂的嵌套循环

时间:2014-06-18 13:07:51

标签: javascript html5 angularjs

我尝试使用Angular.JS循环访问数据,但我无法弄清楚如何使用特定格式循环数据

我会用Java来解释我想要做的事情

示例代码:

int itemCount = 0;
for(int i = 0; i < JSON.length(); i = i + 3) {
    //Loop through this bit of html for every 3 items
    //this is a row
    <div class="row">
    for (int y = itemCount; y < JSON.length(); y++) {
        //This is an item
        <div class="item">
            <!--Some HTML for an item-->
        </div>
        itemCount = y;
    }
    </div>
    itemCount++;
}

基本上,我试图遍历所有项目,每三个创建一个新行,所以HTML看起来像这样:

<div class="row">
    <div class="item">
        <h1>{{person1.name}}</h1>
    </div>
    <div class="item">
        <h1>{{person2.name}}</h1>
    </div>
    <div class="item">
        <h1>{{person3.name}}</h1>
    </div>
</div>
<div class="row">
    <div class="item">
        <h1>{{person4.name}}</h1>
    </div>
    <div class="item">
        <h1>{{person5.name}}</h1>
    </div>
    <div class="item">
        <h1>{{person6.name}}</h1>
    </div>
</div>
...
etc.

Angular循环的排序如下:

<div class="people" ng-repeat="person in personCtrl.people">
     <div class="row" ng-repeat="
                    <!--Create a new row for every three people-->">
         <h1>{{person.name}}</h1>
         <p>{{person.occupation}}</p>
         ...
     </div>
</div>

我知道你必须使用ng-repeat,但我不明白我将如何在Angular.JS中获得这种循环

感谢任何帮助。

编辑:

这是我的数组格式

var people = [
    {
        "name" : "jeff"
        "occupation" : "developer"
        "skills" : [
            {"name" : "Ruby"}
        ]
    }
]

我计划通过一些简单的数据绑定来循环它

ng-repeat="person in arrayCtrl.people"

2 个答案:

答案 0 :(得分:2)

Chunk您的人员阵列在控制器中。

Array.prototype.chunk = function(chunkSize) {
    var array=this;
    return [].concat.apply([],
        array.map(function(elem,i) {
            return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
        })
    );
}

结果:

> [1,2,3,4,5,6,7].chunk(3)
[[1,2,3],[4,5,6],[7]]

如何在Angular.JS中实现

<div class="row" ng-repeat="chunk in Ctrl.chunks">
    <div class="item" ng-repeat="person in chunk.people">
             <h1>{{person.name}}</h1>
             ...
    </div>
</div>

答案 1 :(得分:0)

我不知道完全你想要什么,但你可以尝试这样的事情:

<div ng-repeat="person in arrayCtrl.people">
   <div class="name"> {{ person.name }} </div>
   <div class="skills" ng-repeat="skill in person.skills">
       {{ skill.name }}
   </div>
</div>