AngularJS中具有ng重复的条件内容
我试图为每个字母建立一个带有分隔符的人列表(类似于电话的通讯簿) 我想使用Angular执行类似于此伪代码的操作:AngularJS中具有ng重复的条件内容,angularjs,angularjs-ng-repeat,Angularjs,Angularjs Ng Repeat,我试图为每个字母建立一个带有分隔符的人列表(类似于电话的通讯簿) 我想使用Angular执行类似于此伪代码的操作: <div id="container" ng-init="lastCharacter = ''"> @foreach(person in people) @if(firstCharacter(person.name) != lastCharacter) <div class="divider-item">{{firstCh
<div id="container" ng-init="lastCharacter = ''">
@foreach(person in people)
@if(firstCharacter(person.name) != lastCharacter)
<div class="divider-item">{{firstCharacter(person.name)}}</div>
{{lastCharacter = firstCharacter(person.name)}}
@endif
<div class="person-item">{{person.name}}</div>
@endforeach
</div>
@foreach(人与人之间)
@if(firstCharacter(person.name)!=lastCharacter)
{{firstCharacter(person.name)}
{{lastCharacter=firstCharacter(person.name)}
@恩迪夫
{{person.name}
@endforeach
最简单的方法是什么?我无法使用ng repeat想出一个优雅的解决方案。试试(使用排序列表)
您应该创建一个自定义筛选器,并将分组逻辑移动到其中:
app.filter('groupByFirstLetter',function(){
return function(input){
var result = [];
for(var i = 0;i < input.length; i++){
var currentLetter = input[i][0]
var current = _.find(result, function(value){
return value.key == currentLetter;
});
if(!current){
current = {key: currentLetter, items: []}
result.push(current);
}
current.items.push(input[i]);
}
return result;
};
});
app.filter('groupByFirstLetter',function(){
返回函数(输入){
var结果=[];
对于(变量i=0;i
然后,视图变得简单:
<div ng-repeat="personGroup in people | groupByFirstLetter">
<div class="divider-item">{{personGroup.key}}</div>
<div class="person-item" ng-repeat="person in personGroup.items">
{{person}}
</div>
</div>
{{personGroup.key}
{{person}}
以下是plunker中的一个小示例:
它正在工作,但是它抛出了一些异常,你会明白的。我已经重写了
ng repeat
部分。请检查这会导致容器对每个人重复。我只需要一次容器。您可以将ng repeat
包装在内部div
中,谢谢您的回复。此解决方案会对每个字母组重复“personGroup in people…”div。是否有不需要容器的解决方案AAngelaBBob
@KyleT我用ng repeat start更新了它
<div id="container" >
<div ng-repeat="person in people">
<div class="divider-item"
ng-if="$index == 0 || ($index > 0 && firstCharacter(person.name) != firstCharacter(people[$index-1].name))">{{firstCharacter(person.name)}}</div>
<div class="person-item">{{person.name}}</div>
</div>
</div>
app.filter('groupByFirstLetter',function(){
return function(input){
var result = [];
for(var i = 0;i < input.length; i++){
var currentLetter = input[i][0]
var current = _.find(result, function(value){
return value.key == currentLetter;
});
if(!current){
current = {key: currentLetter, items: []}
result.push(current);
}
current.items.push(input[i]);
}
return result;
};
});
<div ng-repeat="personGroup in people | groupByFirstLetter">
<div class="divider-item">{{personGroup.key}}</div>
<div class="person-item" ng-repeat="person in personGroup.items">
{{person}}
</div>
</div>