编程语言
首页 > 编程语言> > javascript-检查选项选择ng-repeat

javascript-检查选项选择ng-repeat

作者:互联网

我需要检查ng-repeat内的值数组的长度,取决于这一点,我必须添加或< option>或< optgroup>.

ng-repeat看起来像这样:

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

有什么线索如何使用角度模板吗?

提前致谢

解决方法:

因为只允许您< option>或< optgroup>在< select>中.

实现此目的的一种方法是将两个单独的ng-repeats与ng-if结合使用,但这会弄乱值的顺序.

最合适的方法是将ng-repeat-start / ng-repeat-end与ng-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

标签:angularjs,select,angularjs-ng-repeat,javascript
来源: https://codeday.me/bug/20191027/1948418.html