简体   繁体   English

选中选项ng-repeat

[英]check option select ng-repeat

I need to check the length of an array of values inside ng-repeat, depends of that, I have to add or an <option> or <optgroup> . 我需要检查ng-repeat中的值数组的长度,取决于,我必须添加或<option><optgroup>

The ng-repeat look like this: ng-repeat看起来像这样:

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

And the 'countries' is an array of objects that looks like this: 'countries'是一个对象数组,如下所示:

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

The code should look like this, but in angular way: 代码看起来应该是这样的,但是有角度的方式:

<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>

Any clue how to do it with angular template? 任何线索如何使用角模板?

Thanks in advance 提前致谢

This question is tricky since you are only allowed <option> or <optgroup> inside <select> . 这个问题很棘手,因为只允许在<select>使用<option><optgroup> <select>

One way to achieve this is to have two separate ng-repeat s in combination with ng-if , but this will mess up the order of values. 实现这一目标的一种方法是将两个单独的ng-repeatng-if结合使用,但这会弄乱数值的顺序。

The most appropriate way is to use ng-repeat-start / ng-repeat-end in combination with ng-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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM