在AngularJS中处理嵌套的ng-repeat

时间:2016-01-07 07:29:01

标签: angularjs

我是Angular js的新手。尝试以下列方式使用ng-repeat

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

app.controller('myCtrl', function ($scope) {
    $scope.names = ["Emil", "Tobias", "rajeev", "sandeep","deepak"];
});

<div class="dynamicTile" ng-app="myApp" ng-controller="myCtrl">
    <div class="row">
        <div class="col-sm-6 col-xs-6">
            <div id="{{ 'tile' + $index }}" class="tile" ng-repeat="x in names">
                <h1>myNewTile</h1>                       
            </div>
        </div>
    </div>
</div>    

它给了我这样的结构

myNewTile
myNewTile
myNewTile
myNewTile
myNewTile

我希望每个row只包含two tiles。对于third and fourth tile,应创建新的row,依此类推。像这样的东西

myNewTile   myNewTile
myNewTile   myNewTile
myNewTile 

1 个答案:

答案 0 :(得分:1)

您有两种选择:

第一个解决方案

只需将ng-repeat放入您的专栏div

<div class="dynamicTile" ng-app="myApp" ng-controller="myCtrl">
    <div class="row">
        <div class="col-sm-6 col-xs-6" ng-repeat="x in names">
            <div id="{{ 'tile' + $index }}" class="tile">
              <h1>myNewTile</h1>                       
            </div>
        </div>
    </div>
 </div>

Bootstrap将负责其余部分。

或第二个解决方案

当每个列的高度由于内容而不相同时,第一个解决方案的问题将出现,然后Bootstrap将无法执行列的正确对齐。所以你可以使用这个。

您可以先对列表进行整理,然后在其中放置两个ng-repeat

// An helper function to collate the list 
Array.prototype.collate = function(size) {
  var list = [];

  angular.forEach(this, function(item, i) {
    if (i % size === 0) {
      list[Math.floor(i / size)] = [item];
    } else {
      list[Math.floor(i / size)].push(item);
    }
  });

  return list;
};

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

app.controller('myCtrl', function($scope) {
  var names = ["Emil", "Tobias", "rajeev", "sandeep", "deepak"];
  $scope.collatedNames = names.collate(2);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<div class="dynamicTile" ng-app="myApp" ng-controller="myCtrl">
  <div class="row" ng-repeat="names in collatedNames">
    <div class="col-xs-6" ng-repeat="x in names">
      <div id="{{ 'tile' + $index }}" class="tile">
        <h1>myNewTile</h1> 
      </div>
    </div>
  </div>
</div>