SoFunction
Updated on 2025-04-08

AngularJS implementation solution to add index to ng-Options

This article describes the solution to AngularJS implementation of ng-Options plus index. Share it for your reference, as follows:

There is a child in the Angularjs communication group who knows how to add an index $index to Angular select ng-Options like Angularjs' ng-Repeat.

In fact, for this problem, Angular itself does not provide variables such as $index for use. But it doesn't mean that we have no solution to this problem.

To change this problem from an angle, what we need is the subscript of the js array, so if we can add subscripts to the object, we can solve it using the label of the expression as the option.

But the first impression reminds me of this is that the js array is originally a key/value object, but the key is subscripted by the array, so there is a design as follows:

html:

<pre>{{ a | json }}</pre>
<select ng-model="a" ng-options=" as getDesc1(key,value) for (key,value) in t"></select>

js:

$scope.getDesc1 = function(key, value) {
  return (parseInt(key, 10) + 1) + "->" + ;
};

Unfortunately, if you use it as a key/value object for JavaScript, then the key will be unordered, so the unordered subscript appears as follows:

<select ng-model="a" ng-options=" as getDesc1(key,value) for (key,value) in t " class="ng-valid ng-dirty">
 <option value="0" >1-&gt;jw_companyTalent</option>
 <option value="1" >2-&gt;jw_reportgroup</option>
 <option value="10" >11-&gt;jw_ads</option>
 <option value="11" >12-&gt;jw_jobcomment</option>
 <option value="12" >13-&gt;jw_companyInfo</option>
 ....
</select>

So this cannot be solved. Fortunately, the blogger has another trick. ngOptions supports Angularjs filter, so we can add an order field to the data source object as the sequence number. And you can see in an Angular issue 2 years ago that Angular has fixed issue, and the option will generate the array in subscript order.

html:

<pre>{{ b | json }}</pre>
<select ng-model="b" ng-options=" as getDesc(l) for l in t | index "></select>

js:

var app = ('plunker', []);
('MainCtrl', function($scope) {
   $ = [{
    "field": "jw_companyTalent"
   }, {
    "field": "jw_reportgroup"
   }];
   $ = function(l) {
    return  + "->" + ;
   };
}).filter("index", [
   function() {
    return function(array) {
     return (array || []).map(function(item, index) {
       = index + 1;
      return item;
     });
    };
   }
]);

This option is generated in an orderly manner, and we finally solved it perfectly, so this article will also end. At the end attached to the runnable demoplnkr ngOptions index;

I hope this article will be helpful to everyone's AngularJS programming.