使用ng-repeat进行选择时的预选择选项

时间:2020-05-21 09:14:58

标签: angularjs

当我使用ng-repeat重复选择选项时,如何预先选择一个选项:

<select data-ng-model="info.country" ng-change="changeCountry()" name="country" required>
<!-- <option selected disabled hidden value=''></option> -->
     <option data-ng-repeat="country in countries" value="{{country.id}}">{{country.countryName}}</option>
</select>

data-ng-model返回数字3,方法ng-change="changeCountry()"在其实现中使用相同的数字。

我需要预先选择的项目是3而不是1(由于它是一个数组,因此将减少1,但是我想您已经明白了)

我需要预选项目。这可能吗,又怎么能达到这样的结果?

CodePen here.

2 个答案:

答案 0 :(得分:1)

我设法使用ng-options实现了这一目标:

<select ng-options="country.id as country.countryName for country in countries" ng-model="info.country" ng-change="changeCountry()" name="country" required></select>

答案 1 :(得分:1)

ng-repeat上的

<options>id转换为字符串。这就是为什么它不起作用的原因。

{"country":3}{"country":"3"}

您可以使用ng-options解决此问题:

 <select data-ng-model="info.country" 
            ng-change="changeCountry()" name="country"             
            ng-options="c.id as c.countryName for c in countries"            
            required>

    </select>