Angularjs如何设置选择默认值 [英] Angularjs how to set the default value for select

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

问题描述

我有以下对象:

defaults = {
0 : {
    id : 10,
    value : "string 1"
    },
1 : {
    id : 22,
    value : "string 2"
    }
}

我要遍历这个对象,并将其显示为一个选择框。

I want to iterate over this object and display it as a select box.

<select ng-model="selectedValue" ng-options="obj.id as obj.value for obj in defaults">
   <option value="">---Select option-----</option>
</select>

我试图做到的,是在默认情况下选择字符串'2'。但是,这是行不通的。
我的问题是事实了selectedValue是一个字符串:

What I'm trying to achieve is to select 'string 2' by default. But it does not work. The problem I have is the fact the selectedValue is a string:

$scope.selectedValue = "string 2";

这是我从文档了解到了selectedValue必须是同一个对象。但不幸的是,这是不可能的。在我的情况了selectedValue必须是一个字符串。
换句话说,我需要与选项的名称进行操作而已,我不关心ID。
我试图用NG-重复。它甚至工作,但显示一个空的选项,并用NG重复是一个很好的办法做到这一点,我不认为。

From what I learned from the documentation the selectedValue must be the same object. But unfortunately, it is not possible. In my case selectedValue must be a string. In other words I need to operate with the name of the option only, I don't care about id. I tried to use ng-repeat. It even works but displays an empty option and I don't think using ng-repeat is a good way to do it.

任何意见,将大大pciated AP $ P $。

Any advice will be appreciated greatly.

推荐答案

如果你想在了selectedValue 变量包含的价值,而不是ID,那么你不应该使用 obj.id为obj.value ,但 obj.value为obj.value

If you want the selectedValue variable to contain the value, and not the ID, then you should not use obj.id as obj.value, but obj.value as obj.value.

这篇关于Angularjs如何设置选择默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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