闲来无事,斗争一下 select
标签,其中 ngOptions
是关键指令,可指定数据源,需要注意的是使用 ngOptions 指令的同时需要指定 ngModel
, ngModel
用来绑定数据,比如:ng-model=”contry” ,在选中对应的county后,选定的值会绑定到 $scope.country 上面。
我们看一下 ngOptions ,用法比较复杂,引用一下官方文档中的说明:
ng-options
内容格式
- 对于数组数据源
- label for value in array
- select as label for value in array
- label group by group for value in array
- select as label group by group for value in array track by trackexpr
- 对于对象数据源
- label for (key , value) in object
- select as label for (key , value) in object
- label group by group for (key, value) in object
- select as label group by group for (key, value) in object
关键词含义
array / object
:用来便利的数据对象或者数组;value
:遍历数据源时对应数组中的每个项目或者对象中的每个属性值;key
: 遍历数据源时对象中的属性名称;label
:下拉列表中呈现的值,一般都是变量的值(诸如value.propertyName);select
: 对应绑定到select中model的值,如果不选默认跟value一致;group
::指定字段用来分组;trackexpr
: 一般针对对象数组,用来标记数组中的唯一对象;
示例
定义数据源
angular.module('selectExample', []) .controller('ExampleController', ['$scope', function ($scope) { $scope.colors = [ {name: 'black', shade: 'dark'}, {name: 'white', shade: 'light'}, {name: 'red', shade: 'dark'}, {name: 'blue', shade: 'dark'}, {name: 'yellow', shade: 'light'} ]; $scope.myColor = $scope.colors[2]; // red }]);
生成不许为空的列表
<select ng-model="myColor" ng-options="color.name for color in colors"> </select>
生成允许为空的列表
<select ng-model="myColor" ng-options="color.name for color in colors"> <option value="">-- choose color --</option> </select>
按照shade分组的列表
<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors"> </select>
初始化选中指定元素
<select ng-init="myColor = myColor || colors[0]" ng-model="myColor" ng-options="color.name for color in colors"> </select>
注意事项
- 不建议
select as
和trackexpr
共用; - 大多数情况 option 标签 value 为数组索引,但选中元素后model中对应的值则为选中对象;