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

标签 javascript angularjs

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

我创建了一个包含国家/地区对象列表的数组。在 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/

相关文章:

javascript - 如何使用AngularJS的多个ajax调用($http)从单个php文件请求数据?

javascript - 尝试检测第二次单击复选框时出现停止传播问题

javascript - Laravel/Moment - 如何确定夏令时期间是否created_at?

angularjs - 仅将类添加到 AngularJS 中的特定 ng-repeat

javascript - Ionic 应用程序中的分离服务不起作用

javascript - 多个类的选择不起作用

javascript - 如何将显示表动画化为无高度或零高度?

javascript - 替换后动画至高度 0

AngularJS 观察 DOM 变化

javascript - ng-repeat 数据绑定(bind)中的 AngularJS 问题