Reputation: 997
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.
Upvotes: 5
Views: 35366
Reputation: 5060
Here's a sample Fiddle, which works with a basic controller assigning some values. Although you don't have a full code sample I expect not using ng-model
is the issue you're facing.
function TodoCtrl($scope) {
$scope.fields = [{"id":"id1", "text":"text1"}, {"id":"id2", "text":"text2"}];
$scope.choice = null;
}
And the HTML
<div ng-app>
<div ng-controller="TodoCtrl">
<h2>Chosen = {{ choice }}</h2>
<select ng-options="field.id as field.text for field in fields" ng-model="choice"></select>
</div>
</div>
What you should probably take from this is that, ng-options
requires ng-model
to work, otherwise it will just do nothing.
Upvotes: 3
Reputation: 454
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>
Upvotes: 10