The example in this article describes the solution of AngularJS adding index to ng-Options. Share it with everyone for your reference, the details are as follows:
A child in the Angularjs exchange group asked how to add an index $index to Angular select's ng-Options like Angularjs's ng-Repeat.
In fact, for this problem It is said that Angular itself does not provide variables such as $index for use. But that doesn’t mean we don’t have solutions to this problem.
Putting this problem into perspective, all we need is the subscript of the js array, so if we can add a subscript to the object and use an expression as the label of the option, we can solve the problem.
But the first impression reminds me that the js array is originally a key/value object, but the key is the array subscript, so we have the following design:
html:
<pre class="brush:php;toolbar:false">{{ a | json }}
js :
$scope.getDesc1 = function(key, value) { return (parseInt(key, 10) + 1) + "->" + value.field; };
But unfortunately, if you use it as a key/value object for JavaScript, the key will be unordered. Therefore, the unordered subscripts appear as follows:
<select ng-model="a" ng-options="l.field as getDesc1(key,value) for (key,value) in t " class="ng-valid ng-dirty"> <option value="0" >1->jw_companyTalent</option> <option value="1" >2->jw_reportgroup</option> <option value="10" >11->jw_ads</option> <option value="11" >12->jw_jobcomment</option> <option value="12" >13->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 to mark the subscript as the serial number. And you can see in an Angular issue from 2 years ago that Angular has fixed the issue, and the option will generate the array in subscript order.
html:
<pre class="brush:php;toolbar:false">{{ b | json }}
js:
var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.t = [{ "field": "jw_companyTalent" }, { "field": "jw_reportgroup" }]; $scope.getDesc = function(l) { return l.order + "->" + l.field; }; }).filter("index", [ function() { return function(array) { return (array || []).map(function(item, index) { item.order = index + 1; return item; }); }; } ]);
The options are generated in an orderly manner, and finally we can solve it perfectly, so this article will also come to an end. At the end, the runnable demoplnkr ngOptions index is attached;
The above is the solution of AngularJS adding index to ng-Options. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!