2015-09-01 120 views
3

我需要檢查ng-repeat內部數值的數組的長度,取決於此,我必須添加或者<option><optgroup>檢查選項選擇ng-repeat

的NG-重複這個樣子的:

<select name="countries"> 
    <option ng-repeat="country in countries">{{ country.country_name }}</option> 
</select> 

和「國家」爲對象的數組,看起來像這樣:

[ 
    { 
     country_name: "Argentina" 
     language: Array[2] 
     locale_code: "AR" 
    }, 
    { 
     country_name: "Austria" 
     language: Array[1] 
     locale_code: "AR" 
    }, 
    .... 
    .... 
] 

的代碼應該是這樣的,但在角度的方式:

<select name="countries"> 
    for (var i; i < countries.length; i++) { 
     if (countries[i].languages.length > 1) { 
     <optgroup value="{{ i }}" label="{{ country.country_name }}"> 
     for (var j; j < countries[i].languages.length; i++) { 
     <option value="{{ countries[i].languages[j].value }}">{{ countries[i].languages[j].name }}</option> 
     } 
     </optgroup> 
     } else { 
     <option value="{{ countries[i].languages[0].value }}">{{ countries[i].languages[0].name }}</option> 
     } 
    } 
</select> 

任何線索如何使用角模板做到這一點?

在此先感謝

+0

你可以只用NG-IF = 「country.languages.length == 1」和ng-if =「country.languages.length> 1」,就像你在非角度模板上使用它的方式一樣 – Black0ut

+0

這樣我必須做兩個ng-repeat,一個用於選項,另一個用於optgroup ......它'我們都會重複,對嗎? –

+0

如果是分組選項,你也可以看看https://docs.angularjs.org/api/ng/directive/ngOptions groupBy在可選選項 – ThibaudL

回答

4

這個問題棘手,因爲你只允許內部<select><option><optgroup>

實現此目的的一種方法是將兩個單獨的ng-repeatng-if結合使用,但這會混淆值的順序。

最適當的方法是結合使用ng-repeat-start/ng-repeat-endng-if

<select ng-model="selectedLanguage"> 
    <optgroup ng-repeat-start="country in countries" 
      ng-if="country.language.length > 1" 
      label="{{country.country_name}}"> 
    <option ng-repeat="lang in country.language" 
      value="{{lang}}">{{lang}}</option> 
    </optgroup> 
    <option ng-repeat-end 
      ng-if="country.language.length === 1" 
      value="{{country.language[0]}}"> 
    {{country.language[0]}} 
    </option> 
</select> 

Demo

+0

我在代碼中檢查它,謝謝你的迴應。我會讓你知道 –

+0

真棒解決方案! –