Ng-options select the list value set to the id of my choice and bind it correctly using ng-model

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 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 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.

+5
source share
1 answer

I had the same problem. And it looks like p.id will only work in one place, either in select or in trackexpr . The only way this worked for me (the value was set to id ) was as follows:

 <select ng-model="selectedPerson" ng-options="p as p.name for p in People track by p.id"></select> 

Although the code for selecting a person with id = 1 would look pretty ugly:

 $scope.setTo1 = function () { $scope.selectedPerson = $scope.People.filter(function (item) { return item.id == 1 })[0]; } 

Here is the jsfiddle .

This is because you need to assign ng-model to the same element that you have in the ng-options collection, since they are compared by reference. This is from the angular documentation :

Note: ngModel is compared by reference, not by value. This is important when binding to an array of objects. See an example in jsfiddle .

So, I finally refused and allowed angular to set the parameter value for what it needed, as that would allow me to make assignemnet as simepl as: $scope.selectedPersonId = 1

+7
source

Source: https://habr.com/ru/post/1202736/


All Articles