0

I have a drop-down-menu as follows:

<select ng-model="myDropDown"
        ng-options="c.id as c.name for c in myUnsortedList | orderBy:'name'"></select>

It is populated with an unsorted list (with member objects having id and name properties) sorted with respect to the name property.

An annoying problem is that AngularJS puts an empty option at the top (depicted to the left).

As described here the solution is to initialize the list in the controller code:

$scope.myDropDown = myUnsortedList[0].id;
                                   ^
                                   |
                                   +----- Index 0 selected just to take
                                          an index that always is available

This removes the empty item but has the side effect of making an arbitrary element the pre-selected item in the drop-down menu (right image), since myUnsortedList is unsorted and not in the same order as the sorted list set in ng-options; hence any element could have index 0 in the unsorted list.

I would like AngularJS to not pre-select an arbitrary element in the sorted menu (i.e. select the first item instead), while avoiding the empty element. How can this be done easily?

Community
  • 1
  • 1
Gruber
  • 4,478
  • 6
  • 47
  • 74

1 Answers1

1

An annoying problem is that AngularJS puts an empty option at the top. solution is to initialize the list in the controller code.

Alternative solution to this, you can put placeholder instead,

<select ng-model="myDropDown" ng-options="c.id as c.name for c in myUnsortedList | orderBy:'name'">
    <option value="">--Select--</option>
</select>

side effect of making an arbitrary element the pre-selected item in the drop-down menu (right image), since myUnsortedList is unsorted and not in the same order

$scope.mySortedList = $filter('orderBy')($scope.myUnsortedList,'name');//don't forget to inject $filter in your controller
$scope.selected = 2;

markup:

ng-options="c.id as c.name for c in mySortedList"
ram1993
  • 979
  • 1
  • 9
  • 13