【发布时间】:2020-09-07 21:40:18
【问题描述】:
编辑以添加一个明确的问题:我有一个一定长度的平面数组,我想将它放入 tr/td 类型的视图中?这也可能在引导网格或类似的东西中。本质上,我想在一系列长度为 n 的块中显示一个平面数组。
关于 SO,这个问题有很多变体,但我还没有真正看到任何一个很好的解释:如何使这项工作或为什么不能。所以我做了一个非常simple example 来证明这个问题。它会呈现,但如果您检查日志,您会看到错误(太大而无法链接到)。
index.html:
<!DOCTYPE html>
<html lang="en-US" ng-app="rowApp">
<head><title>Angular chunks</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js" integrity="sha384-c4XWi4+MS7dBmCkPfB02+p/ExOF/ZBOfD2S4KR6mkmpBOg7IM6SUpA1KYZaVr7qE" crossorigin="anonymous"></script>
<script src="app.js"></script>
</head>
<body>
<table ng-controller="rowController" border="1" style="width:30%">
<tr ng-repeat="people_chunk in people | chunk:4">
<td ng-repeat="person in people_chunk">{{person.name}}</td>
</td>
</table>
</body>
</html>
app.js:
var rowApp = angular.module('rowApp', ['filters']);
angular.module('filters', []).
filter('chunk', function () {
return function (items, chunk_size) {
var chunks = [];
if (angular.isArray(items)) {
if (isNaN(chunk_size))
chunk_size = 4;
for (var i = 0; i < items.length; i += chunk_size) {
chunks.push(items.slice(i, i + chunk_size));
}
} else {
console.log("items is not an array: " + angular.toJson(items));
}
return chunks;
};
});
rowApp.controller('rowController',
function ($scope, $http) {
$http.get("/people.json")
.then(function(response) { $scope.people = response.data; });
});
people.json:
[{"name": "a"}, {"name": "b"}, {"name": "c"}, {"name": "d"},
{"name": "1"}, {"name": "2"}, {"name": "3"}, {"name": "4"}]
然后您可以使用python -m SimpleHTTPServer 9000 提供所有这些,然后转到http://localhost:9000/
【问题讨论】:
-
你想把一个数组分成 4 份,然后用 ng-repeat 重复它们吗?
-
真的不清楚你的目标是什么。
-
您收到的错误消息可能是由于无限循环。您可以查看是否使用断点,您的过滤器会一直执行到 Angular 将其杀死。
-
@K.Gkinis 好的,这似乎是可能的。但我不清楚为什么。 (我在开头提出了一个明确的问题)
-
我认为这是特定于演示的逻辑,应该使用 CSS 来完成
标签: javascript angularjs