Reputation: 1173
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
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
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
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
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
Reputation: 15403
Your way
<select ng-options="item.ID as item.Title for item in items" ng-model="someModel"></select>
Alternate way
<select ng-model="selectedItem">
<option ng-repeat="item in items" value="{{item.ID}}">{{item.Title}}</option>
</select>
Upvotes: 1
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