AngularJS嵌套ng-repeat

时间:2015-02-12 06:24:11

标签: javascript angularjs

我有一个像这样的HTML:

 <div class="fields-plan"data-ng-repeat="roomname in assign.roomname">  
         <section>
         <span>Room: {{roomname}}</span>        
         </section>   
    <ul data-ng-repeat="room in assign.rooms.roomname">
       <li>
       {{room.room}}
       </li>
   <ul>
 </div>

我的角度控制器看起来像这样:

    var room = {"1.2":
                [
                    {room: "1.2.1"},
                    {room: "1.2.2"},
                    {room: "1.2.3"}
                ],
        "1.3": [
            {room: "1.3.1"},
            {room: "1.3.2"},
            {room: "1.3.3"}
        ]};


    var keys = Object.keys(room);

    this.roomname = keys;
    this.rooms = room;

在我的第二次重复中,它不起作用,我怎么能根据房间名循环,从第一次重复输出?

3 个答案:

答案 0 :(得分:1)

你的第二个ng-repeat需要取第一个ng-repeat值而不是直接取房间名,所以你的第二个ng-repeat应该是这样的:

代码:

 <div class="fields-plan"data-ng-repeat="(key, value) in assign.rooms">  
         <section>
         <span>Room: {{key}}</span>        
         </section>   
    <ul data-ng-repeat="room in value">
       <li>
       {{room.room}}
       </li>
   <ul>
 </div>

答案 1 :(得分:1)

您可以通过稍微重新格式化Json然后使用以下代码来实现此目的:

关键是在第二次ng-repeat中使用第一次ng-repeat的值,而不是尝试引用第一次收集。

HTML:

<div ng-controller="MyCtrl">

    <div class="fields-plan" ng-repeat="room in rooms">  
             <section>
             <span>Room: {{room.name}}</span>        
             </section>   
        <ul ng-repeat="subroom in room">
           <li>
           {{room.subRoom}}
           </li>
       <ul>
     </div>
</div>

的javascript:

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.rooms = [ { name : "1.2",
                       subRoom: [
                    "1.2.1","1.2.2","1.2.3"],
                     }, { name: "1.3",
        subRoom: [
            "1.3.1","1.3.2","1.3.3"]}];
}

小提琴演示:http://jsfiddle.net/0pnam0wj/

答案 2 :(得分:1)

这是你想要的吗?

plnkr

<div data-ng-repeat="(roomnamePrefix, roomname) in rooms">  
         <section>
         <span>Room: {{roomnamePrefix}}</span>        
         </section>   
    <ul data-ng-repeat="room in roomname">
       <li>
       {{room.room}}
       </li>
   <ul>
 </div>