如何在angularjs中按字母顺序显示名称

时间:2017-06-29 14:09:15

标签: angularjs

我从数据库中获取一个数组,我正在使用angularjs ng-repeat打印数组名称,我想显示这些名称
ñ
      纳雷什
    小号
      Sateesh
      桑迪普
      苏雷什
 

[
  {
    "name": "suresh",
  },
  {
    "name": "naresh",
  },
  {
    "name": "sateesh",
  },
  {
    "name": "sandeep",
  }
]
I want to display the names as below using ng-repeat
 N
  Naresh
s
  Sateesh
  sandeep
  suresh

1 个答案:

答案 0 :(得分:0)

您必须预处理阵列并使用嵌套的ng-repeat:

在您的控制器中:

$scope.datas = [
                    { "name": "suresh"  },
                    { "name": "naresh"  },
                    { "name": "sateesh" },
                    { "name": "sandeep" }
                ];

$scope.processed = process($scope.datas);

console.log($scope.processed);

function process(arr) {
    var processed = {};
    arr.forEach(item => {
        var key = item.name[0];
        processed[key] = processed[key] || [];
        processed[key].push(item.name);
    });
    return processed;
}

在你的模板中:

<ul>
    <li ng-repeat="(key, value) in processed">
        {{key}}
        <ul>
            <li ng-repeat="item in value | orderBy "> {{item }} </li>
        </ul>                           
    </li>
</ul>