Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating select with JSON in AngularJS with ng-options

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.

like image 334
elykl33t Avatar asked Jun 13 '14 19:06

elykl33t


People also ask

What is ng options?

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.


1 Answers

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>

like image 151
GabrielG Avatar answered Oct 03 '22 14:10

GabrielG