我有一系列的信件说" A到我"我希望将其分成预定义大小的批次并按以下格式打印。我试图使用嵌套的ng-repeat来实现相同的目标 -
A B C D
E F G H
我
但相反,它总是一直打印前四个字母,如下所示 -
A B C D
A B C D
A B C D
有人可以指出我做错了什么吗?任何替代/更好的解决方案也值得赞赏。
以下是我的代码 -
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Nested ng-repeat</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js"></script>
<style>
.solid-border {border:solid; margin: 2px; width: 100px;}
.inline-display {display: inline}
</style>
</head>
<body ng-app="limitToExample">
<script>
angular.module('limitToExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.batchSize = 4;
$scope.letters = ['A','B','C','D','E','F','G','H','I'];
$scope.getNumberOfBatches = function(){
var res = Math.ceil($scope.letters.length / $scope.batchSize);
var arr = [];
for(var i = 0; i < res; i++) {
arr.push(i);
}
return arr;
};
$scope.getNextBatchSize = function(batchNumber){
if(batchNumber * $scope.batchSize < $scope.letters.length){
return $scope.batchSize;
}
return $scope.batchSize - ((batchNumber * $scope.batchSize) - $scope.letters.length)
};
}]);
</script>
<div ng-controller="ExampleController">
<div class="solid-border" ng-repeat="i in getNumberOfBatches()">
<div class="inline-display" ng-repeat="letter in letters | limitTo: (($parent.$index + 1) * batchSize) | limitTo: (0 - getNextBatchSize($parent.$index + 1))">
{{letter}}
</div>
</div>
</div>
</body>
</html>
答案 0 :(得分:1)
您可以创建一个过滤器,以行列方式划分数组,其中行数等于batchSize
<强> JAVASCRIPT 强>
.filter('partition', function() {
return function(array, size) {
var newArray = [], i, next;
for(i = 0; i < array.length; i = next) {
next = i + size;
newArray.push(array.slice(i, next));
}
return newArray;
};
});
<强> HTML 强>
<div ng-repeat="row in letters | partition:batchSize track by $index">
<span ng-repeat="letter in row track by $index">{{letter}}</span>
</div>