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裏的對象就有數據了,
能夠初始化選中對應的項。