Here is what seems to be bothering a lot of people (including me).
When using the ng-options
directive in AngularJS to fill in the options for a &
I have struggled with this problem for a while today. I read through the AngularJS documentation, this and other posts and a few of blogs they lead to. They all helped me grock the finer details, but in the end this just seems to be a confusing topic. Mainly because of the many syntactical nuances of ng-options
.
In the end, for me, it came down to less is more.
Given a scope configured as follows:
//Data used to populate the dropdown list
$scope.list = [
{"FirmnessID":1,"Description":"Soft","Value":1},
{"FirmnessID":2,"Description":"Medium-Soft","Value":2},
{"FirmnessID":3,"Description":"Medium","Value":3},
{"FirmnessID":4,"Description":"Firm","Value":4},
{"FirmnessID":5,"Description":"Very Firm","Value":5}];
//A record or row of data that is to be save to our data store.
//FirmnessID is a foreign key to the list specified above.
$scope.rec = {
"id": 1,
"FirmnessID": 2
};
This is all I needed to get the desired result:
Notice I did not use track by
. Using track by
the selected item would alway return the object that matched the FirmnessID, rather than the FirmnessID itself. This now meets my criteria, which is that it should return a numeric value rather than the object, and to use ng-options
to gain the performance improvement it provides by not creating a new scope for each option generated.
Also, I needed the blank first row, so I simply added an to the
element.
Here is a Plunkr that shows my work.