我在尝试将自动标题放入 ng-repeat 创建的列表时遇到问题。下面的代码根据排序列表中名称的第一个字母变化创建一个标题。下面的代码会生成标题,但是当我在列表中过滤时,我会遇到标题字母加倍的问题。任何人都可以帮忙吗?
<li ng-repeat="people in address | filter:query | orderBy:orderProp" alphabetical="{{people.name[0]}}" >
<alphabetical-headers-from-name stem="people" listno="$index" path="path" ></alphabetical-headers-from-name>
</li>
var previousRefFirstLetter = "";
myapp.directive('alphabeticalHeadersFromName', function ($compile) {
return {
restrict: 'E',
terminal: true,
scope: { stem: '=',
listno: '=',
path: '='},
link: function (scope, element, attrs) {
var boolAddHeader = false;
//Get current element reference first letter
if(scope.stem.name === undefined || scope.stem.name === null){
var refFirstLetter = "";
}else{
var refFirstLetter = scope.stem.name.charAt(0);
}
//if this is the first element of the list, set the comparison letter to ""
if(scope.listno === 0){
previousRefFirstLetter = "";
}
var prevFirstLetter = previousRefFirstLetter
//compare current letter with previous letter. If there is a difference, we will need to create a header.
if (previousRefFirstLetter.toUpperCase() !== refFirstLetter.toUpperCase()){
boolAddHeader = true;
previousRefFirstLetter = refFirstLetter;
}
//Create header (if required)
if(boolAddHeader){
element.append('<li class="heading">'+refFirstLetter+'</li>');
}
//Create list element.
element.append('<a href="'+ scope.path + scope.stem.id +'">'+scope.stem.name+'</a>');
$compile(element.contents())(scope.$new());
}
}
});