Siddharth
Siddharth

Reputation: 869

how to print alphabets for numbering using ng-repeat

I want to print alphabets for marking options of questions using ng-repeat directive in Angular.

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

$root.options have 4 option, now i want it to be printed like

A: option 1

B: option 2

C: option 3

D: option 4

PS: I am not using HTML list neither I am planning to.

Upvotes: 4

Views: 1955

Answers (2)

Shashank Agrawal
Shashank Agrawal

Reputation: 25807

Here you go:

First define all the alphabets:

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

And then use it:

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

See it working below:

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>

Upvotes: 2

gtlambert
gtlambert

Reputation: 11971

One solution would be to create a string in your $scope as follows:

$scope.alphabet = 'abcdefghijklmnopqrstuvwxyz';

You can then use track by $index in your ng-repeat to access letters from the string as follows:

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

Upvotes: 4

Related Questions