2013-05-15 62 views
2

我試圖將自動頭信息放入ng-repeat創建的列表中時出現問題。下面的代碼根據排序列表中名稱的第一個字母創建標題。下面的代碼會生成標題,但是當我在列表中篩選時,我會遇到問題,其中包含標題字母。誰能幫忙?在Angularjs中添加自動頭信息到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()); 
     } 
    } 
}); 

回答

5

見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>