使用ng重复或ng选项和删除空白选项选择长方体角度

Select box angular using ng-repeat or ng-options and removing blank option

本文关键字:选项 ng 长方体 选择 空白 使用 删除      更新时间:2023-09-26

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

我已经创建了一个带有国家对象列表的数组。在html中,我循环浏览countries数组,并将每个值添加到一个选择框中。

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

如何在数组中只包含2个值?这个答案应该有效,但它没有在html中显示正确的值。也许是因为我一直在使用ng重复,但也许我应该像这个答案所建议的那样使用ng选项?

请参阅下面的代码。

控制器

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>

要删除空选项,您需要在加载此页面时为控制器中的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"

需要创建另一个具有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>