1

I have the json object that is returned from an ajax call:

0: Object
    id: "0-0-0"
    selected: "selected"
    text: "option name"
    value: 0
    __proto__: Object
1: Object
    id: "12-0-0"
    selected: ""
    text: "4C 1.75 16v Tbi ( TCT )"
    value: 59885

I want to populate the options of a select like so:

<option value="0" id="0-0-0" selected="selected">option name </option>

How is this possible with ng-options?

3
  • See my answer below, which assumes that you're actually dealing with an array of objects. If you are really dealing only with a single object returned from the server, please update your question to explain why and how you're using a select for a single option. Commented May 27, 2014 at 16:08
  • Thank you Marc for the very good answer. Yes I am dealing with array of objects. I do however want to ask you, that I have read that it is a bad practice to use ng-repeat in select. So in my case if I want to stick with the id's is it bad to use ng-repeat? Commented May 28, 2014 at 7:43
  • ng-repeat creates a new scope for each iteration, so ng-options is the more efficient choice, but it sounds like in your case you need to use it, and unless you're outputting many, many options, it shouldn't be a problem. Commented May 28, 2014 at 13:37

1 Answer 1

6

ng-repeat makes more sense if you need the id attribute populated by the server response:

HTML:

<select>
    <option ng-repeat="obj in results" id="{{obj.id}}" value="{{obj.value}}"
    ng-selected="obj.selected === 'selected'">{{obj.text}}</option>
</select>

ng-repeat Demo

However, if it's just the data you're after (and don't need to set the id attribute for each option), ng-options would work like this instead:

<select ng-model="selection" ng-options="obj as obj.text for obj in results">
</select>

ng-options Demo

Sign up to request clarification or add additional context in comments.

2 Comments

In the ng-options example, in your Demo, the options value inside the select does not get the object.value. Instead it starts from 0 and adds up for every option...
This is how ng-options works, but what is stored in the ng-model value will be whatever you've set it for in the comprehension expression (the whole object in the demo). If you need the value to be set to something else, then ng-repeat is your better bet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.