我怎样才能对象作为模型angularjs采用NG-关联的选项 [英] How can I associate objects as models using ng-options in angularjs

查看:97
本文介绍了我怎样才能对象作为模型angularjs采用NG-关联的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个对象:颜色和衬衫。

Assume I have two objects: color and shirt.

每个衬衫可以具有多个属性以及多种颜色基本上是彩色对象数组

Each shirt can have multiple properties as well as multiple colors which is basically an array of color objects.

function MyCntrl($scope) {
    $scope.colors = [
        {
            label:"Red",
            value:"r-e-d",
            available:true
        },
        {
            label:"Blue",
            value:"b-l-u-e",
            available:false
        }   
    ];

    $scope.shirts=[{
        size:"M",
        cost:100,
        colors:[ ]
    }
    ]
}

如何使用 NG-选项追加/删除颜色 shirts.color ?

我想联想 scope.color 反对 scope.shirts.color 的对象,这样,如果我改变的东西喜欢的颜色的颜色或code的名称,然后在相关的颜色对应的项目 shirts.colors对象也应该得到自动更新。

I want to associate scope.color objects to scope.shirts.color objects so that if I change something like name of the color or code of the color, then the corresponding items in the associated color objects in shirts.colors should also get updated automatically.

这是我所知道的关于 NG-选项 NG-模型,我必须要创建新对象颜色并设置其值基于什么是在选择框中选择,但这些对象将独立的颜色对象,并改变颜色的物体不会衬衣更新相应的对象。

From what I know about ng-options and ng-model, I will have to create new objects for colors and set its values based on what is selected in the select box, but those objects will be independent of the color objects and changing the color objects will not update the corresponding objects in shirts.

感谢您提前为您的答复。

Thank you in advance for your responses.

推荐答案

您可以使用 NG-选项为直接:

Color: <select multiple ng:model="shirt.colors" ng:options="c.value as c.label for c in colors"></select>

下面是一个Plunker:<一href=\"http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=$p$pview\">http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=$p$pview

Here is a Plunker: http://plnkr.co/edit/FQQxrSE89iY1BnfumK0A?p=preview

更新

和有关源代码的修改颜色:如果衬衫的颜色,你只存储值,这将是非常难以检测什么项目是改变和重新选择它选项​​(改变选中的项目取消选择,因为AngularJS不知道变化的原因)。

And about editing of source colors: if in shirt's color you store just value, it would be extremely hard to detect what was item was changed and re-select it in options (changed selected item unselects because AngularJS don't know reason of change).

作为变通方法,您可以选择对象,而不是值。我已经更新plunker。

As workaround you can select objects, not values. I've updated plunker.

这篇关于我怎样才能对象作为模型angularjs采用NG-关联的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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