ng-select 对象及其在 angularjs 中的属性 [英] ng-select with an object and its properties in angularjs

查看:32
本文介绍了ng-select 对象及其在 angularjs 中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图弄清楚如何使用数组 if 对象作为 ng-select 指令的键值

I have been trying to figure out how to use an array if objects as the key values for an ng-select directive

这是我要使用的数据

$scope.selectValues [
    {name: "Options 1", value: "11"}, 
    {name: "Options 2", value: "22"}
    {name: "Options 3", value: "33"}
];

我希望输出是

<select>
    <option value="11">Options 1</option>
    <option value="22">Options 2</option>
    <option value="33">Options 3</option>
</select>

谁能解释一下如何做到这一点?并显示指令设置的示例?我看过文档,但他们没有适合这个模型的例子.

Can anyone explain how to do this ? and show a an example of the directive set up? I have looked at the docs but they don't have an example that fits for the this model.

推荐答案

ng-options 支持基于数组和对象的数据源.例如:

ng-options supports both array and object based data source. For example:

基于数组的数据源:

$scope.options = ["Blue", "Red", "Yellow"]

<select ng-model="selected"
        ng-options="for o in options">

基于对象的数据源:

$scope.options = {
  "Blue": "color_1",
  "Red": "color_2",
  "Green": "color_3"
}

<select ng-model="selected"
        ng-options="name for (name, value) in options">

但是,您对基于数组的选项使用了不兼容的数据结构.你可以这样使用:

However, you are using an incompatible data structure for the array based option. You can use like this:

<select ng-model="selected"
        ng-options="o.name for o in options">

并将所选值用作 selected.value.(selected 绑定到数组中的对象之一).如果您想通过 HTTP 提交表单,这将不起作用,因此在这种情况下,您应该将选项转换为上述数据结构之一.

and use the selected value as selected.value. (selected is bound to one of the objects in the array). This won't work if you want to submit the form via HTTP, so in this case you should convert the options to one of the data structure mentioned above.

我在此处包含了这三种用法:http://plnkr.co/IEBQkqJNifY5MZWloDP6

I've included these three usage here: http://plnkr.co/IEBQkqJNifY5MZWloDP6

所以我今天再次查看了文档,找到了处理原始数据结构的方法.

So I looked at the docs again today and found the way to work with your original data structure.

<select ng-model="selected"
        ng-options="o.value as o.name for o in options">

plnkr 也更新了.

The plnkr is updated also.

这篇关于ng-select 对象及其在 angularjs 中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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