【问题标题】:Select box angular using ng-repeat or ng-options and removing blank option使用 ng-repeat 或 ng-options 选择框角度并删除空白选项
【发布时间】:2016-04-18 15:05:42
【问题描述】:

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

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

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

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

请看下面我的代码。

控制器

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>

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    要删除空选项,您需要在加载此页面以显示默认选定值时从控制器中为 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>
    

    【讨论】:

      猜你喜欢
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多