我有一个 ul 并且我在 li 上应用了 ngRepeart 但我想在每 2 个 li 之后创建一个新的 ul强>像这样。
这可能吗?
<ul>
<li>simth</li>
<li>aryan</li>
</ul>
<ul>
<li>john</li>
<li>mark</li>
</ul>
<ul>
<li>cooper</li>
<li>lee</li>
</ul>
这是我的 angular.js 代码
function myCrtl($scope){
$scope.nameList= [{
name:'simth'
},{
name:'aryan'
},{
name:'john'
},{
name:'mark'
},{
name:'cooper'
},{
name:'lee'
}]
}
最佳答案
AngularJS 中的编程接近于“数据驱动开发”。您的数据不反射(reflect)您想要获得的 HTML 结构,因此更难实现,但并非不可能。我的第一个建议解决方案是更改数据的结构。如果那不是一种选择,请继续阅读。
const myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', $scope => {
$scope.nameList = [
[{name: 'simth'}, {name: 'aryan'}],
[{name: 'john'}, {name: 'mark'}],
[{name: 'cooper'}, {name: 'lee'}]
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<ul ng-repeat="group in nameList">
<li ng-repeat="person in group">{{person.name}}</li>
</ul>
</div>
</div>
备选
如果您无法更改数据结构,您仍然可以这样做。实现一些辅助函数或过滤器:
const myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', $scope => {
$scope.nameList = [
{name: 'simth'},
{name: 'aryan'},
{name: 'john'},
{name: 'mark'},
{name: 'cooper'},
{name: 'lee'}
];
});
myApp.filter('getGroup', () => (array, number) => {
return array.reduce((prev, next, index) => {
if (index % number === 0) { // start a new group
prev.push([next]);
} else {
prev[prev.length - 1].push(next); // add to existing group
}
return prev;
}, []);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<ul ng-repeat="group in nameList | getGroup:2">
<li ng-repeat="person in group">{{person.name}}</li>
</ul>
</div>
</div>
过滤器的作用是:获取数组并将其分成许多数组,每个数组有 2 个元素(这是一个参数,因此您可以稍后重用它)。
关于javascript - 在每第二个 <li> 之后添加 <ul></ul> 并使用 Angular ngRepeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27013260/