我需要检查 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"
},
....
....
]
代码应该是这样的,但是是 Angular :
<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>
任何线索如何使用 Angular 模板来完成?
提前致谢
最佳答案
这个问题很棘手,因为你只被允许 <option>
或 <optgroup>
里面<select>
.
实现此目的的一种方法是使用两个独立的 ng-repeat
s 结合 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>
关于javascript - 检查选项选择ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32327715/