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

ここでプランカーを参照してください: 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 に答える