2

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

1 回答 1

6

在这里看到 plunker: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>
于 2014-04-01T10:38:21.810 回答