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

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

问题描述

我有以下对象:

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-repeat.它甚至可以工作,但显示一个空选项,我认为使用 ng-repeat 不是一个好方法.

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.

任何建议将不胜感激.

推荐答案

如果您希望 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如何为select设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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