ng-repeat这种方式很简单。javascript
写一个select,而后在里面的option标签里加上ng-repeat指令就能够了。html
这种很单一,可是实际应用当中,咱们一般都是键值对这种方式。java
好比option里的value一个值,展现的时候又一个值。那ng-repeat就很差实现了。angularjs
这个时候就应该用ng-options了。sql
JS代码片断json
$scope.options = { 'jsonHead': 'sqls', 'dbName': 'oracle', 'submitType': [ { 'sortValue': 0, 'type': 'sr' }, { 'sortValue': 1, 'type': 'pkgh' }, { 'sortValue': 2, 'type': 'pkgb' }, { 'sortValue': 3, 'type': 'trigger' }, { 'sortValue': 4, 'type': 'job' } ], 'prePath': '', 'fileName': '' }; $scope.selectedIndex = $scope.options.submitType[0];//默认选中第一个
HTML代码片断跨域
<select class="form-control" ng-model="selectedIndex" ng-options="x.type for x in options.submitType"></select>
运行效果:数组
有几个点须要记录一下。oracle
ng-options="x.type for x in options.submitType"函数
这句话的意思是从options.submitType这个数组取值。
in左右的x为变量名。for左边的x.type是我们展现到页面上的属性值
特别须要强调一下,这里的select标签里必定要ng-model绑定一个对象,名字能够任意取
而后就是
$scope.selectedIndex = $scope.options.submitType[0];//默认选中第一个
注释已经说明了。
今天作项目的时候发现本身有另外一种需求,这里再次记录下!
当我们的数组数据只是
以下这样:
{ field:'addInterface', type:'select', text:'接口类型', val:[{val:0,text:'无'},{val:1,text:'ESG'},{val:2,text:'JS跨域调用'},{val:3,text:'其它'}], style:'column' }
那这个时候我们须要初始化默认选中val=1,text='ESG'怎么办?
先写案例1:
<select ng-options="z.text for z in y.val" ng-model="y.field" ng-init="y.field=y.val[0]"> </select>
其实原理跟以前是一致。只是那里用代码实现,这里在init实现。默认选中第一个
而后我们来看升级版:
<select class="form-control" ng-options="z.text for z in y.val" ng-model="y.field" ng-init="y.field=getOptionObj(y.field.text,y.val)"> </select>
$scope.getOptionObj = function(text,arr){ for(var i=0,len=arr.length;i<len;i++){ if(arr[i].text === text){ return arr[i]; } } return arr[0];//返回默认的 };
默认返回第0项。而后根据文本值再返回对应的项。
总结下:两种方式:一种是用代码获取数组里的第0项来初始化。
第二种是在页面写ng-init的时候初始化。
至于函数那种方式,是初始化的时候,自己ng-model里的对象就有数据了,
能够初始化选中对应的项。