使用ng-repeat或ng-options选择框角度并删除空白选项

时间:2016-04-18 15:05:42

标签: javascript angularjs

我在这里找到了很多答案,但非常令人沮丧的是我无法执行它。首先要解释一下我做了什么:

我创建了一个包含国家/地区对象列表的数组。在html中,我循环遍历countries数组并将每个值添加到选择框中。

我只想展示英国和美国,但是我的代码还有第三个选项(空选项)。

如何才能在数组中包含2个值?这个answer should work,但它没有在html中显示正确的值。也许是因为我一直在使用ng-repeat,但也许我应该使用ng-options作为this answer建议?

请参阅下面的代码。

CONTROLLER

this.countries = [
        {name: "United Kingdom"},
        {name: "United States of America"}
    ];

HTML

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

1 个答案:

答案 0 :(得分:1)

要删除空选项,您需要在加载此页面时为控制器指定country ng-model="ctrl.country"以显示默认选定值。

像:

this.countries = [
        {name: "United Kingdom"},
        {name: "United States of America"}
    ];
this.country = this.countries[0].name; // initially show "United Kingdom"

需要创建另一个empty值的选项,以显示为已选择

<select ng-model="ctrl.country">
    <option value="">select one</option>// default to show 
     <option ng-repeat="country in ctrl.countries" value="{{country.name}}">{{country.name}}</option>     
</select>
相关问题