EDIT: My code actually does work, I was just being an idiot with an unrelated problem. Thanks for your input everyone.
So I have an array of JSON objects formatted like this:
[{"id":"id1", "text":"text1"}, {"id":"id2", "text":"text2"},....]
I want to populate an AngularJS select field using these, with the text fields as the display text and the id fields as the values, or whatever binds to the model. I have looked around, but can't for the life of me figure out what I need to do.
Right now I have this for my select, which results in nothing displaying:
<select name="field" ng-model="npe.formData.field" ng-options="field.id as field.text for field in fields">
Doing ng-options this way results in things displaying, but obviously will result in the incorrect value binding to the model:
ng-options="field as field.text for field in fields"
I have seen people talking about using "(key, value)", but I can't wrap my head around how it works.
Definition and Usage. The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.
You'll need (key,value) in case you are repeating through a map, which is not the case - in your example you are iterating an array of objects. An usage of (key,value) would be:
$scope.map={item1:'a',item2:'b'};
...
<li ng-repeat="(id,text) in map">{{id}}) {{text}}</li>
which would render "item1) a" and so on.
Why did you mention the snippet below doesn't work?
ng-options="field.id as field.text for field in fields"
Checkout this fiddle - http://jsfiddle.net/7eqsc/2/, it works like a charm and updates the model with the correct id.
<div ng-app="myApp">
<div ng-controller="myCtrl">
<div ng-repeat="(id,text) in notes">{{text}}</div>
<select ng-model="model.id" ng-options="note.id as note.text for note in notes" ></select>
Selected id:{{model.id}}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With