Search code examples
angularjsng-optionsangularjs-ng-options

ngOptions using basic expression providing odd rendered value


I have the following Object in TypeScript defining some options for a <select> using ng-options:

$scope.sOptions = [
   {
      name: "Female"
   }, 
   {
      name: "Male"
   }];

I provide the following for ng-options to AngularJS:

ng-options="opt.name for opt in sOptions"

This actually works except for the fact that according to the documentation for ng-option, the value should just be the loop counter while building out the <option> elements. However I see the following rendered:

<option value="?" selected="selected"></option>
<option label="Female" value="object:6">Female</option>
<option label="Male" value="object:7">Male</option>

What I'm expecting to see is something like the following:

<option value="0" selected="selected"></option>
<option label="Female" value="1">Female</option>
<option label="Male" value="2">Male</option>

What am I doing incorrectly to have those odd values being produced for the value of the <option> element?

EDIT: After reading the correct answer provided, this other post goes into detail about a similar issue and also how to use track by for this requirement: https://stackoverflow.com/a/30292209/410937


Solution

  • In order to achieve this requirement you have to use track by in ng-select. The track by will help you in binding the select option with a value tag. You should also provide an Unique Id field to track the select option.

    <select ng-model="selectedName" ng-options="item.Name for item in names track by item.Id">
    </select>
    

    In your controller the names object will be like this

    $scope.names = [{Name: "Name1", Id: 0}, {Name: "Name2", Id: 1}, {Name: "Name3", Id: 2}];
    

    In order to initialize the select option you can set the model by

    $scope.selectedName = $scope.names[0];
    

    You can initialize the scope variable only if you use the track by property in select option