Kyle
Kyle

Reputation: 1173

Angular ng-options track by issue

I have a data set of objects that I'm displaying using ng-options. I'm binding the objects ID value to the value using track by

Currently, the data values are being included but they're being displayed with commas. For example...

$scope.items = [
   {ID: '2012', Title: 'Chicago'},
   {ID: '2013', Title: 'New York'},
   {ID: '2014', Title: 'Washington'},
];

<select ng-options="item.Title for item in items track by item.ID">
</select>

But this will render...

<option value="2,0,1,2" label="Chicago">Chicago</option>
<option value="2,0,1,3" label="New York">New York</option>

Why are these commas being added, and how can I remove them?

Upvotes: 4

Views: 7659

Answers (6)

Maverick
Maverick

Reputation: 648

If you want it to be by id then you should use

item.id as item.name for item in items

Upvotes: 0

Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

function MyController($scope){
  $scope.items = [
		                {ID: '2012', Title: 'Chicago'},
		                {ID: '2013', Title: 'New York'},
		                {ID: '2014', Title: 'Washington'},
		             ];
  };
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body ng-controller="MyController">		
		<select ng-model="selectedItem" ng-options="item.ID as item.Title for item in items track by item.ID"></select>
		<br/>{{selectedItem}}
  </body>
  </html>

Following should work:--

  <select ng-model="selectedItem" ng-options="item.ID as item.Title for item in items track by item.ID"></select>

  {{selectedItem}}

Upvotes: 1

manzapanza
manzapanza

Reputation: 6245

Try this:

<select ng-model="selectedItemID" ng-options="item.ID as item.Title for item in items">
</select>

Selected ID: {{selectedItemID}}

Upvotes: 1

trees_are_great
trees_are_great

Reputation: 3911

You want:

<select ng-options="obj.ID as obj.title for obj in items"></select>

Track by just helps angular internally with array sorting. See: stack overflow answer

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15403

Your way

<select ng-options="item.ID as item.Title for item in items" ng-model="someModel"></select>

Fiddle

Alternate way

<select ng-model="selectedItem">
        <option ng-repeat="item in items" value="{{item.ID}}">{{item.Title}}</option>
</select>

Fiddle2

Upvotes: 1

Tomislav
Tomislav

Reputation: 3211

You don't need track by:

<select ng-options="i.ID as i.Title for i in items" ng-model="someModel"></select>

After rendering you will have:

<option value="2012">Chicago</option>
<option value="2013">New York</option>

Upvotes: 9

Related Questions