如何使用 ng-repeat 打印字母编号

how to print alphabets for numbering using ng-repeat

我想使用 Angular 中的 ng-repeat 指令打印字母表以标记问题的选项。

<div ng-repeat="options in $root.options">
  //print alphabets in sequence here//:{{options}}
</div>

$root.options 有 4 个选项,现在我希望它打印成

A: 选项 1

B: 选项 2

C: 选项 3

D: 选项 4

PS:我没有使用 HTML 列表,我也不打算使用。

一种解决方案是在 $scope 中创建一个字符串,如下所示:

$scope.alphabet = 'abcdefghijklmnopqrstuvwxyz';

然后您可以在 ng-repeat 中使用 track by $index 来访问字符串中的字母,如下所示:

<div ng-repeat="options in $root.options track by $index">
  {{ alphabet[$index] }}: {{ options }}
</div>

给你:

首先定义所有的字母:

$scope.letterArray = [];
for(var i = 0; i < 26; i++) {
    $scope.letterArray.push(String.fromCharCode(65 + i));
}

然后使用它:

<div ng-repeat="options in $root.options">
    {{letterArray[$index]}}: option {{$option}}
</div>

查看下面的工作情况:

var myApp = angular.module("sa", []);

myApp.controller("foo", function($scope) {
  
  $scope.letterArray = [];
  
  for (var i = 0; i < 26; i++) {
    $scope.letterArray.push(String.fromCharCode(65 + i));
  }

  $scope.options = [{
    name: "hello foo"
  }, {
    name: "hello bar"
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="foo">
  <div ng-repeat="option in options">
    {{letterArray[$index]}}: {{option.name}} {{$index}}
  </div>
</div>