Is it possible to add a dynamic attribut id
to an option
, when I use ng-options
in a select
to loop my list and generate my dropdown? It works, if I use an ng-repeat
loop, because there I can put the attribut id
directly in the option
tag an increment it with $index
. Is this also possible with ng-options
? Here is my code:
angular.module("myApp", []).controller("myController", function($scope) {
$scope.selectedOption1;
$scope.selectedOption2;
$scope.myList = [{
text: "1"
}, {
text: "2"
}, {
text: "3"
}, {
text: "4"
}, {
text: "5"
}, ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<!--BUILD DROPDOWN WITH NG-OPTIONS LOOP-->
<select ng-model="selectedOption" ng-options="option as option.text for option in myList"></select>
<!--BUILD DROPDOWN AND SET ATTRIBUT ID WITH NG-REPEAT LOOP-->
<select ng-model="selectedOption2">
<option id="option_{{$index}}" ng-repeat="option in myList">{{option.text}}</option>
</select>
</div>
Screenshot of both select
(red border are the id's):
Any ideas? Thanks.
You can use the track by
option :
<select ng-model="selectedOption" ng-options="obj.text for obj in myList track by obj.value">
But then, you have to modify your object a little bit :
$scope.myList = [{
text: "1",
value: "option_1"
}, {
text: "2",
value: "option_2"
}, {
text: "3",
value: "option_3"
}, {
text: "4",
value: "option_4"
}, {
text: "5",
value: "option_5"
}, ];
This should do the trick.
EDIT 2 For those who want a fast answer, you also can do this :
<select ng-model="selectedOption" ng-options="obj.text for obj in myList track by option + obj.text">
And in the js file add :
$scope.option = 'option_';
$scope.myList = [{
text: "1"
}, {
text: "2"
}, {
text: "3"
}, {
text: "4"
}, {
text: "5"
}, ];