Angular ng-options track by issue

I have a dataset of objects that I display using ng-options. I bind the value of the object ID to the value withtrack by

Currently, data values ​​are included, but they are displayed with commas. For instance...

$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 it will do ...

<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 added and how to remove them?

+4
source share
6 answers

You do not need to track:

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

After rendering, you will get:

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

Do you want to:

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

Tracking just helps angular internally with array sorting. See stack overflow response

+1
source

:

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

Selected ID: {{selectedItemID}}
+1

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

Fiddle

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

Fiddle2

+1

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>
Hide result

: -

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

  {{selectedItem}}
+1
source

If you want this to be by id, you should use

item.id as item.name for an item in items

0
source

All Articles