0

I like to build an select element for ordering data. I like to automatically create options for any property of an object.

Code

<select class="order" ng-model="model.order">
    <option value="{{key}}" ng-repeat="(key, value) in dataItems[0]">{{key}}</option>
</select>

Data

dataItem: {
 { firstname: "beate", lastname: "lind" }
 { firstname: "john", lastname: "rich" }
}

In this case it will take the first object and generate my select options.

MR.ABC
  • 4,712
  • 13
  • 44
  • 88

2 Answers2

2

It's not correct to use ng-repeat on a select tag. Please refer to the ng-options attribute which should behave more consistently and give you the desired result:

https://docs.angularjs.org/api/ng/directive/select

Cranio
  • 9,647
  • 4
  • 35
  • 55
0

@Cranio is correct, ngOptions is the correct method when using select. Using your code this is what it'd look like.

$scope.dataItem = [
 { firstname: "beate", lastname: "lind" }
 { firstname: "john", lastname: "rich" }
]

<select ng-model="model.order" ng-options="(name.firstname + ' ' + name.lastname) for name in dataItem">
    <option value="">[-- select --]</option>
</select>

Live DEMO

This SO post has a lot of helpful answers if you get stuck (there are several other things you can do with ngOptions) How do I set the value property in AngularJS' ng-options?

Community
  • 1
  • 1
EnigmaRM
  • 7,523
  • 11
  • 46
  • 72