选择多个对象并保存到NG-模型 [英] Select multiple objects and save to ng-model

查看:109
本文介绍了选择多个对象并保存到NG-模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML

<select ng-model="contact.groups" 
        ng-options="item.id as item.name for item in groups" 
        ng-multiple="true" multiple>

        <option value="">Choose groups</option>
</select>

contact.groups 包含分配给联系人组的列表:

contact.groups contains a list of groups assigned to the contact:

[
   {
     id: 145,
     name: 'FooBar
   }
]

是所有可用组的列表。第一个问题是在NG-选项item.id将显示不属于该组的正确的ID,但似乎从0(列表中的第一组),1(列表中的第二组),计数等。

groups is a list of all available groups. First problem is that item.id in ng-options displays not the correct ID of the group but seems to count from 0 (first group in list), 1 (second group in list), etc

第二个问题是contact.groups是没有考虑到,有在选择字段中没有$ P $对选定的组。

Second problem is that contact.groups is not taken into account, there is no pre-selected groups in the select field.

请参阅此琴 http://jsfiddle.net/Jy643/1/

任何想法如何处理这个问题?

Any ideas how to handle this problem?

推荐答案

ngOptions通过全等比较对象,这意味着你的模型组必须在 $ scope.groups <组中的一个参考/ code>:

ngOptions compares objects by strict equality, meaning your model group needs to be a reference to one of the group in $scope.groups:

function MyCtrl($scope) {

    $scope.test = "Das ist ein Test";
    $scope.groups = [{id: 142, name: 'Foo'},{id: 143, name: 'Bar'}, {id: 144, name: 'Bas'}];

    $scope.contact = {name: 'Bob', groups: [{id: 143}]};
    $scope.contact = {name: 'Bob', groups: $scope.groups[1]};
}

<大骨节病> PLUNKER

这篇关于选择多个对象并保存到NG-模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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