ng-option小解

ng-option 有数组,对象两种情况,但目前只接触过数组

数组:

label for value in array

分为一般数组和对象数组

一般数组:

<select ng-model="myAddress" ng-options="item for item in address"></select>

$scope.address= ["北京", "天津", "河北"];

发现第一项为空

dom树如下:

解析: 1.当未设置初始值时,初始值及option列表第一项为空,默认第一项被选 2.value等于label

设置初始值方法:

1.$scope.myAddress= $scope.address[0];

注: 初始值必须得是数组中的某一项,否则无效

则变为:

2.新增option

<select ng-model="myAddress" ng-options="item for item in address">
  <option value="" disabled="">请选择地址</option>
</select>

(值得一提的是这种方法只能新增一个option,多写的不会出现)

变为:

disable的option会变为不可选的灰色,此种方法应用面更广

对象数组:

<select ng-model="myColor1" ng-options="color.name for color in colors"></select>

$scope.colors = [
  {name:'black', shade:'dark'},
  {name:'white', shade:'light', notAnOption: true},
  {name:'red', shade:'dark'},
  {name:'blue', shade:'dark', notAnOption: true},
  {name:'yellow', shade:'light', notAnOption: false}];

dom树如下:

解析: 写法与一般数组不同,value为label所属的对象

---------------------------------------------------------------------------------------------------------------------------------------------------------

label group by group for value in array(选项分组)

<select ng-model="myColor2" ng-options="color.name group by color.shade for color in colors"></select>

                           label                    分组依据属性     

$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light', notAnOption: true},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark', notAnOption: true},
{name:'yellow', shade:'light', notAnOption: false}
];

可见按照shade属性进行了分组

----------------------------------------------------------------------------------------------------------------------------------------------------------

label disable when disable for value in array(将部分option设为disable)

<select ng-model="myColor3" ng-options="color.name disable when color.notAnOption for color in colors"></select>

                        label                          disable依据属性

$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light', notAnOption: true},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark', notAnOption: true},
{name:'yellow', shade:'light', notAnOption: false}
];

可以看出当notAnOption未false时不可点击

--------------------------------------------------------------------------------------------------------------------------------------------

select as label for value in array(设置value)

<select ng-model="myColor4" ng-options="color.shade as color.name for color in colors"></select>

                       value             label

可见shade成了value,name成了label

-------------------------------------------------------------------------------------------------------------------------------------------------

原文地址:https://www.cnblogs.com/yanze/p/6071332.html