AngularJS:每n个元素

时间:2017-04-15 14:03:42

标签: javascript html angularjs

我有一个像这样的javascript数组,并尝试使用AngularJS生成嵌套的<div>

var arr = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"];

我想用这样的每3个元素划分。

<div class="parent">
  <div class="child">abc</div>
  <div class="child">def</div>
  <div class="child">ghi</div>
</div>
<div class="parent">
  <div class="child">jkl</div>
  <div class="child">mno</div>
  <div class="child">pqr</div>
</div>
<div class="parent">
  <div class="child">stu</div>
</div>

我可以这样做吗?

2 个答案:

答案 0 :(得分:1)

以下是使用ng-repeat

在angularJs中实现它的完整代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
</head>

<body>
<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <div class="parent" ng-repeat="item in chunkArray">
      
  <div class="child" ng-repeat="child in item">{{child}}</div>
 
</div>

  </div>
</div>
<script>
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
 var data = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"];
  $scope.chunkArray = chunk(data,3);
  function chunk(array, size) {
  var result = []
  for (var i=0;i<array.length;i+=size)
    result.push( array.slice(i,i+size) )
  return result;
  }
 
});
</script>
</body>
</html>

答案 1 :(得分:1)

一种方法是根据itemsArray.length/maxItems创建一个虚拟数组,并将该虚拟数组用于外部ng-repeat ...然后对项目使用limitTo过滤器。

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

app.controller('MainCtrl', function($scope) {
  $scope.maxItems = 3;
  $scope.items = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"];
  $scope.parentArr = new Array(Math.ceil($scope.items.length/$scope.maxItems));    
  
});
.parent{border: 1px solid #ccc; padding:10px}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
  <div class="parent" ng-repeat="par in parentArr track by $index">
    <div ng-repeat="item in items |limitTo: maxItems : $index*maxItems">{{item}}</div>
  </div>
</div>