在Angular中基于ng-repeater索引查找数组的项

Finding item of array base on the ng-repeater index in Angular

本文关键字:索引查找 数组 ng-repeater Angular      更新时间:2023-09-26

在我的应用程序中,我有2个对象数组。layout阵列用于创建twitter引导布局。该数组如下所示:

 $scope.layout = [
  {c:[{size:12}]},
  {c:[{size:2},{size:3},{size:4},{size:3}]},
  {c:[{size:3},{size:5},{size:4}]}
];

可以看到这个数组是如何在jsbin中工作的。另一个数组是items数组,这个数组如下所示:

 $scope.items =[
   {row:1,column:0,names:['Jack','Daniel']},
   {row:3,column:3,names:['Eli','Bill']},
   {row:2,column:1,names:['Fred','David']}
];

这是我使用的重复器:

<div ng-repeat="(ri,r) in layout" class="row">
  <div ng-repeat="(ci,c) in r.c" class="col-md-{{c.size}} col-sm-{{c.size}} col-xs-{{c.size}} col-lg-{{c.size}}  bi"> Row{{ri}}-Column{{ci}}
         //Maybe other repeater come here
  </div>
</div>

现在我想当我想在row 1 column 0中显示Jack , Daniel时,这个1和0是第一和第二中继器的中继器中的r和c。因此,当中继器创建row 2 column 1时,也在$ scope上重复。条目并查找相关名称。但是我不知道如何在$scope.item中找到项目。这是jsbin

你可以这样做:

<div ng-repeat="(ri,r) in layout" class="row">
  <div ng-repeat="(ci,c) in r.c" class="col-md-{{c.size}} col-sm-{{c.size}} col-xs-{{c.size}} col-lg-{{c.size}} bi">
    {{getNames(ri, ci)}}
  </div>
</div>

其中getNames在控制器中定义:

$scope.getNames = function(r, c) {
  var items = $scope.items;
  for (var i = 0; i < items.length; i++) {
    if (items[i].row == r && items[i].column == c) {
      return items[i].names;
    }
  }
  return '';
};

演示:http://jsbin.com/sumuwigo/1/edit