我在尝试将自动标头放入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());
        }
    }
});

最佳答案

在这里查看punker:http://plnkr.co/edit/WSXhDoLK8LXRnYZfHls9?p=preview

var data =  [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
];

  $scope.members = _.reduce(
    data,
    function(output, name) {
      var lCase = name.name.toLowerCase();
      if (output[lCase[0]]) //if lCase is a key
        output[lCase[0]].push(name); //Add name to its list
      else
        output[lCase[0]] = [name]; // Else add a key
      return output;
    },

    {}
  );

的HTML
 <div ng-repeat="(header,data) in members">
    <h1>{{header}}</h1>

    <section ng-repeat="member in data">
      {{member.name}}
    </section>

  </div>

09-28 14:10