我在这里找到了很多答案,但非常令人沮丧的是我无法执行它。首先解释一下我做了什么:
我创建了一个包含国家/地区对象列表的数组。在 html 中,我循环遍历国家数组并将每个值添加到选择框。
我只想显示英国和美国,但是我的代码还有第三个选项(空选项)。
如何才能在数组中只包含 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>
最佳答案
要删除空选项,您需要在加载此页面时为 Controller 中的 ng-model="ctrl.country"
值分配 country
以显示默认选择的值。
喜欢:
this.countries = [
{name: "United Kingdom"},
{name: "United States of America"}
];
this.country = this.countries[0].name; // initially show "United Kingdom"
或需要创建另一个具有空
值的选项以显示为选定状态
<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>
关于javascript - 使用 ng-repeat 或 ng-options 选择框 Angular 并删除空白选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36697792/