When using Angular, I am trying to create a select list where the value corresponds to the actual id of an object. I want to bind this correctly with the ng-model directive.
Here is my attempt:
<select ng-model="selectedPersonId"
ng-options="p.id as p.name for p in People track by p.id"></select>
$scope.People = [
{ name : "Fred", id : 1 },
{ name : "Joe", id : 2 },
{ name : "Sandra", id : 3 },
{ name : "Kacey", id : 4 },
{ name : "Bart", id : 5 }
];
$scope.setTo1 = function(){
$scope.selectedPersonId = 1;
}
In this select option, the value matches the correct id (id of the person in people) and the text is accurate. However, the binding does not work. Setting the value of $scope.selectedPersonId does not reflect in the selection on the list.
I have found a workaround:
<select ng-model="selectedPersonId"
ng-options="p.id as p.name for p in People"></select>
This method works, where setting $scope.selectedPersonId reflects changes on the list. But in this case, the id used in the select option value is not the actual id of the person!
<option value="0">Fred</option> <!--option value is 0, not Fred's true id -->
<option value="1" selected="selected">Joe</option>
...
My goal is to use it like the first example while still having Angular use the true id of the person in the select option value, rather than an index or other identifier.
If you're wondering why I need it to work this way, it's because the id is sent to an API and the model can be set via query string, so it must work with these requirements.