With angular, I would like to make a select list with a value that accepts the identifier of my choice (the actual id property of the object), and I would like to associate it correctly with the ng-model directive.
Here is what I 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; }
http://jsfiddle.net/b7dyadnr/
Here, the parameter value is selected - the correct value (value is the identifier of a person in people), and the text is correct. But the binding does not work, so if I set the value of $ scope.selectedPersonId, the selection does not appear in the list.
I know that I can make it work as follows:
<select ng-model="selectedPersonId" ng-options="p.id as p.name for p in People"></select>
http://jsfiddle.net/rgtbn2f5/
It works there, I can set $ scope.selectedPersonId, and the changes are reflected in the list. But then the identifier used in the selection list option value is not the identifier of the actual person!
<option value="0">Fred</option> <option value="1" selected="selected">Joe</option> ...
I want to use it like this, except that I want angular to use the true identifier of the person in the value of the selection option, not the index of the array or anything else that it uses.
If you are wondering why I want to use it like this, this is because the identifier is sent to the API, and the model can also be set using querystring, so I have to make it work as follows.