adamors
adamors

Reputation: 2656

Angular ng-repeat in dropdown

I'm trying to do this with ng-repeat in Angular:

   <select ng-model="selected_item">
        <option ng-repeat="item in items" value="{{item.id}}"
                ng-change="doSomething(selected_item)">
        {{item.name}} - {{item.another_attribute}}
        </option>
    </select>

and getting the error No controller: ngModel.

Usually I construct dropdowns with ng-options but since the label of the options are made up of two different attributes, it doesn't work.

<select ng-model="selected_item" 
        ng-options="item.id as item.name for item in items" 
        ng-change="doSomething(selected_item)">

As you can see I cannot use two attributes here for the label.

Any ideas?

Upvotes: 2

Views: 7372

Answers (1)

Yoshi
Yoshi

Reputation: 54649

You can concatenate strings in the label expression. So

ng-options="item.id as (item.name + '-' + item.another_attribute) for item in items" 

should work just fine.

quick demo: http://jsbin.com/OKoviMA/1/


To be more precise, the label expression is a real angular expression, so you could for example also apply a filter or call a controller method, even passing the current itteration value as a parameter.

Upvotes: 8

Related Questions