AngularJS如何获取父级索引

时间:2014-12-11 13:55:35

标签: angularjs indexing

我有一些webapp要改变。我使用ng-repeat进行了一些更改,新的JSON看起来像这样:

[  
   {  
      "styl":"nowoczesny",
      "dzieci":[  
         {  
            "id":53,
            "bookmark":true,
            "rodzina":"Nekko",
            "page":1
         },
         {  
            "id":69,
            "bookmark":true,
            "rodzina":"Krak",
            "page":2
         },
         {  
            "id":81,
            "bookmark":true,
            "rodzina":"Oxen",
            "page":3
         },
         {  
            "id":93,
            "bookmark":true,
            "rodzina":"Spirala",
            "page":4
         }
      ]
   },
   {  
      "styl":"klasyczny",
      "dzieci":[  
         {  
            "id":109,
            "bookmark":true,
            "rodzina":"Vello",
            "page":5
         },
         {  
            "id":127,
            "bookmark":true,
            "rodzina":"Renzo",
            "page":6
         },
         {  
            "id":135,
            "bookmark":true,
            "rodzina":"Zenit",
            "page":7
         }
      ]
   }
]
像这样的HTML:

<ul>

    <li ng-repeat="l in list">
      {{l.styl}}&nbsp;
    <ul>
      <li ng-repeat="dziecko in l.dzieci | filter:search "  
          ng-class="{active:isActiveTab(dziecko)}" ng-click="openItem(dziecko)">
                                {{dziecko.rodzina}}&nbsp;
                                <b>{{dziecko.page}}</b>
      </li>
   </ul>
   </li>

尽管openItem方法,一切正常但它的第一个版本看起来像这样:

$scope.openItem = function(item) {

        var index = $scope.list.indexOf(item),
                length = $scope.list.length;

        $scope.opened = item;
        $scope.next = $scope.list[index+1];
        $scope.prev = $scope.list[index-1];
    };

我应该如何修改它以使其适用于上面的html代码。我尝试$ index但是角度抛出一个错误。 (点击列表中的子项目后,我需要打开一个新的pdf页面。)

提前谢谢!

1 个答案:

答案 0 :(得分:0)

$index应该是您需要的项目的索引,但是如果您想从$ scope获取它,您也需要父节点的索引,它可以由$ parent。$ index in嵌套的ng-repeat(详见here)。

所以代码将是这样的: HTML

<li ng-repeat="l in list">
      {{l.styl}}&nbsp;
    <ul>
      <li ng-repeat="dziecko in l.dzieci | filter:search "  
          ng-class="{active:isActiveTab(dziecko)}" ng-click="openItem($parent.$index, dziecko)">
                                {{dziecko.rodzina}}&nbsp;
                                <b>{{dziecko.page}}</b>
      </li>
   </ul>
 </li>

JS

$scope.openItem = function(parentIndex, item) {

    var index = $scope.list[parentIndex].dzieci.indexOf(item),
        length = $scope.list.length;

    $scope.opened = item;
    if(index == 0) {
       $scope.next = $scope.list[index+1];
     $scope.prev = $scope.list[$scope.list.length - 1];
   } else if(index == $scope.list.length - 1 ) {
     $scope.next = $scope.list[0];
     $scope.prev = $scope.list[index-1];
   } else {
     $scope.next = $scope.list[index+1];
     $scope.prev = $scope.list[index-1];
   }
};

要保持上一个和下一个,你应该正确使用边界索引。

codepen:http://codepen.io/anon/pen/gbrrgQ