With angular I would like to make a select list with value that takes the id of my choice (actual id property of an object) and I would like to bind it correctly with ng-model directive.
Here is what I've tried :
<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;
}
Here select option value is the correct value (value is the id of person in people) and text is correct. But the binding doesn't work so if I set the value of $scope.selectedPersonId the selection is not reflected on the list.
I know I can make it work like this :
<select ng-model="selectedPersonId"
ng-options="p.id as p.name for p in People"></select>
There it works I can set $scope.selectedPersonId and the changes are reflected on the list. But then the id used in the select list option value is not the id of the actual person !
<option value="0">Fred</option> <!--option value is 0 which is not the true id of fred -->
<option value="1" selected="selected">Joe</option>
...
I want to use it like this except that I want angular to use the true id of the person in the select option value and not the index of the array or whatever thing it uses.
If you wonder why I want to use it like this it is because the id is sent to an API and the model can also be set using querystring so I must make it work like this.