Daud Daud - 1 month ago 6
AngularJS Question

How to get label=value using ng-options with simple array

I have an array like

$scope.years = ['1900', '1901', '1902'];


If I use
<select ng-model="chosenYear" ng-options="choice for choice in years"></select>

I get

<option value="0">1900</option>
<option value="1">1901</option>
<option value="2">1902</option>


where index of the array becomes the '
value
' of options. How can I have both
value
and
label
equal (both being 1900, 1902, 1902, etc) ?

A similar question has an accepted answer, but it doesn't do this thing at all.

Angular version : 1.2.16

Answer

What you want is <select ng-model="chosenYear" ng-options="choice as choice for choice in years"></select>

EDIT: since above does not work in angular 1.2.16 try below

<select ng-model="chosenYear" ng-options="choice for choice in years track by choice"></select>

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.years = ['1900', '1901', '1902'];
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">


<select ng-model="chosenYear" ng-options="choice for choice in years track by choice"></select>
</div>



</body>
</html>

Comments