选择多个对象并保存到 ng-model [英] Select multiple objects and save to ng-model
问题描述
HTML:
contact.groups
包含分配给联系人的组列表:
groups
是所有可用组的列表.第一个问题是 ng-options 中的 item.id 显示的组 ID 不正确,但似乎从 0(列表中的第一组)、1(列表中的第二组)等开始计数
第二个问题是没有考虑contact.groups,select字段中没有预先选择的组.
看这个小提琴http://jsfiddle.net/Jy643/1/
任何想法如何处理这个问题?
ngOptions 通过严格相等来比较对象,这意味着您的模型组需要引用 $scope.groups
中的组之一:
function MyCtrl($scope) {$scope.test = "Daist 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]};}
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
contains a list of groups assigned to the contact:
[
{
id: 145,
name: 'FooBar
}
]
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
Second problem is that contact.groups is not taken into account, there is no pre-selected groups in the select field.
See this fiddle http://jsfiddle.net/Jy643/1/
Any ideas how to handle this problem?
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]};
}
这篇关于选择多个对象并保存到 ng-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!