atconway atconway - 1 year ago 62
AngularJS Question

ngOptions using basic expression providing odd rendered value

I have the following

defining some options for a

$scope.sOptions = [
name: "Female"
name: "Male"

I provide the following for

ng-options=" for opt in sOptions"

This actually works except for the fact that according to the documentation for
, the
should just be the loop counter while building out the
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
of the

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:

Answer Source

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">

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download