如何在Angular.js选择框中有一个默认选项 [英] How to have a default option in Angular.js select box

查看:198
本文介绍了如何在Angular.js选择框中有一个默认选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了Google,但在此找不到任何内容。

I have searched Google and can't find anything on this.

我有这段代码。

<select ng-model="somethingHere" 
        ng-options="option.value as option.name for option in options"
></select>

对于这样的一些数据

options = [{
   name: 'Something Cool',
   value: 'something-cool-value'
}, {
   name: 'Something Else',
   value: 'something-else-value'
}];

输出是这样的。

<select ng-model="somethingHere"  
        ng-options="option.value as option.name for option in options" 
        class="ng-pristine ng-valid">

    <option value="?" selected="selected"></option>
    <option value="0">Something Cool</option>
    <option value="1">Something Else</option>
</select>

如何将数据中的第一个选项设置为默认值,以便获得这样的结果。

How is it possible to set the first option in the data as the default value so you would get a result like this.

<select ng-model="somethingHere" ....>
    <option value="0" selected="selected">Something Cool</option>
    <option value="1">Something Else</option>
</select>


推荐答案

您只需使用ng-init 像这样

<select ng-init="somethingHere = options[0]" 
        ng-model="somethingHere" 
        ng-options="option.name for option in options">
</select>

这篇关于如何在Angular.js选择框中有一个默认选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆