2016-10-11 90 views
0

我有一个下拉菜单如下:预先选择第一项目

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

它填充有一个未排序的列表(与具有idname属性成员对象)根据name财产进行排序。

一个恼人的问题是AngularJS在顶部放置了一个空白选项(如左图所示)。

作为described here溶液是初始化在控制器代码的列表:

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

这消除了空项,但具有使任意的元件预先选择项目的副作用在下拉菜单(右图)中,由于myUnsortedList未排序,且与ng-options中设置的排序列表不同;因此任何元素都可以在未排序列表中具有索引0。

我希望AngularJS不要在排序菜单中预先选择一个任意元素(即选择第一个项目),同时避免空元素。这如何轻松完成?

回答

1

一个令人讨厌的问题是AngularJS在顶部放置了一个空白选项。 解决方案是初始化控制器代码中的列表。

替代解决这个,可以把占位符代替,使得任意元素中 预选择的项目的下拉式菜单(右图像)的

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

副作用,因为myUnsortedList是未排序的和不 以相同的顺序

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

加价:

ng-options="c.id as c.name for c in mySortedList" 
相关问题