ng-repeat索引,按字母顺序排列

Mic*_*son 3 javascript angularjs

我希望以$index字母格式输出而不是编号.

<div ng-repeat="name in names">{{$index}}</div>

这可能吗?

Mic*_*son 5

这是我找到的解决方案:

使用Javascript:

// the alphabet    
$scope.alphabet['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

// get the index and return the letter of the alphabet
$scope.getLetter = function(index) {

  return $scope.alphabet[index];

};
Run Code Online (Sandbox Code Playgroud)

HTML:

<div ng-repeat="name in names">{{getLetter($index)}}</div>
Run Code Online (Sandbox Code Playgroud)

编辑(感谢@TheShalit和@patrick):

使用Javascript:

// get the index and return the letter of the alphabet
$scope.getLetter = function(index) {

  return String.fromCharCode(65+index);

};
Run Code Online (Sandbox Code Playgroud)

HTML:

<div ng-repeat="name in names">{{getLetter($index)}}</div>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/cLto7mff/

  • 您可以使用`String.fromCharCode(64 + index)`来获取没有字母数组的char (5认同)
  • 我会使用`String.fromCharCode(65 + $ index)`因为索引是从0开始的,否则字母以'@'开头.你可以在http://jsfiddle.net/cLto7mff/看到一个样本 (4认同)