如何使用data-ng-repeat从A到Z获取索引值?

时间:2013-09-15 17:23:57

标签: javascript angularjs

我一直在索引值之前使用如下:

{{ $index }}

我真正需要的是获取一个数字而不是获得一个从A到Z的大写字符的数字。应该没有问题,因为我最多只有10个重复的东西。

有人能告诉我怎么做吗?

3 个答案:

答案 0 :(得分:7)

将以下方法添加到您的范围:

$scope.indexChar = function (index) {
    return String.fromCharCode(65 + index);
};

然后在您的视图中使用它:

{{ indexChar($index) }}

这里是小提琴:http://jsfiddle.net/Xs5Qn/

答案 1 :(得分:4)

您可以使用函数String.fromCharCode(n),包含在过滤器中:

angular.module('myApp').filter('fromCharCode', function() {
  return function(input) {
    return String.fromCharCode(input);
  };
});

在模板中,您可以这样称呼它:

{{($index + 65) | fromCharCode}}  // 65 is the letter A

编辑:您还可以创建一个更具体的过滤器,只返回大写字母:

angular.module('myApp').filter('letterFromCode', function() {
  return function(input) {
    var code = input % 26;
    return String.fromCharCode(65 + code);
  };
});

答案 2 :(得分:1)

只需使用一个代表字母表的数组。

$scope.alphabet = ["A", "B", "C", .... "Z"];

并在模板中使用它:

{{ alphabet[$index] }}