2014-10-08 24 views
0

我有可用的選擇項目的數組:AngularJS - 如何在select中預選值?

// Default available date formats 
     $scope.dateformats = [ 
      { 
       code: 'YY.MM.DD', 
       name: 'YY.MM.DD' 
      }, 
      { 
       code: 'DD.MM.YY', 
       name: 'DD.MM.YY' 
      } 
     ]; 

我試圖爲默認預定值是這樣的:

$scope.actualDateformat = $scope.dateformats[0].code; 
<select ng-options="dateformat.name for dateformat in dateformats" ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)"> 
    <option style="display:none" value="">{{actualDateformat}}</option> 
</select> 

的問題是, 「預選」 值出現列表中作爲第一個選項標籤>

<option style="display:none" value="">{{actualDateformat}}</option> 

從剩下的兩個動態添加項目中選擇任何一個後,第一個選項中的文本會附加上所選項目的文本(和值)。

請問如何解決?

我想有結果是這樣的:

<select> 
    <option value="YY.MM.DD">YY.MM.DD</option> 
    <option value="DD.MM.YY" selected>DD.MM.YY</option> 
</select> 

感謝您的幫助。

+0

你有沒有試過https:// docs。angularjs.org/api/ng/directive/ngSelected – 2014-10-08 08:29:39

回答

1

變化:

<select ng-options="dateformat.name for dateformat in dateformats" 
     ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)"> 
    <option style="display:none" value="">{{actualDateformat}}</option> 
</select> 

要:

<select ng-options="dateformat.code as dateformat.name for dateformat in dateformats" 
     ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)"> 
</select> 

這樣,選擇應該認識該項目,其中dateformat.code比賽actualDateformat

This blog has some good examplesng-options

給你舉個例子:

假設:

$scope.array = [ 
    { key: 1, value: 'Display text 1!' }, 
    { key: 2, value: 'Display text 2!' }, 
    { key: 3, value: 'Display text 3!' } 
] 

然後,使用下列選項:

<select ng-options="item.key as item.value for item in array" ng-model="result"> 

會導致:

<select ...> 
    <option value="1">Display text 1!</option> 
    <option value="2">Display text 2!</option> 
    <option value="3">Display text 3!</option> 
</select> 

$scope.result竟被d設置爲這些選項元素的'value屬性。
如果初始化$scope.result2,應選擇"Display text 2!"

+0

我喜歡這個答案,因爲它提供了一個很好的博客文章關於各種選項以及 – Wiz 2017-10-04 10:36:42

2

這裏是FIDDLE

你的問題是你選擇該對象的整個對象不是代碼字段。

dateformat.name for dateformat in dateFormats 
    label : dateformat.name 
    object : dateformat 

dateformat.code as dateformat.name for dateformat in dateformats 
    label : dateformat.name 
    object : dateformat.code 

此外,我不明白的optiondisplay:none的需要。您可以選擇dateformat.code這樣。

<select ng-options="dateformat.code as dateformat.name for dateformat in dateformats" ng-model="actualDateformat" ng-change="changeDateFormat(dateformat)"> 
</select> 
+0

是的,這就是我已經回答。 – Cerbrus 2014-10-08 08:43:23

+1

那麼?當你在這裏寫作時,我正忙於jsfiddle。我不想浪費我的時間只是爲了顯示另一個答案。我想你知道我沒有複製你的答案。 – 2014-10-08 08:46:03

相關問題