当ng-model为null时,在select中设置默认值 [英] Set default value in select when the ng-model is null

查看:177
本文介绍了当ng-model为null时,在select中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是角色的新手,我正试图设置一个默认状态,以便在我的ng-model为null时选择。基本上我想在模型为空时将其设置为无。我尝试了以下代码,但它无效。

I'm new to angular and i'm trying to set a default state to select when my ng-model is null. Basically I want to set it to 'None' if the model is empty. I tried the below code but it's not working.

<select ng-init="item.carType | item.carType='none'" ng-model="item.carType">
    <option value="none">None</option>
    <option value="manual">Manual</option>
    <option value="auto">Auto</option>                      
</select>


推荐答案

试试这个:

<select ng-init="item.carType = item.carType || 'none'" ng-model="item.carType">
    <option value="none">None</option>
    <option value="manual">Manual</option>
    <option value="auto">Auto</option>                      
</select>

那就是说,按照文档,这可能是对ngInit的误用。执行此操作的正确方法是使用控制器(或服务,如果它来自的位置)中的合理值初始化模型。

That said, per the docs, this is probably a misuse of ngInit. The proper way to do this would be to initialize your model with sane values in the controller (or service, if that's where it came from).

这篇关于当ng-model为null时,在select中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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