Select multiple objects and save to ng-model

2019-05-25 04:35发布

问题:

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?

回答1:

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



回答2:

Try using 'track by tracking_expression' into ngOptions (also run on ngRepeat) that allow match objects by expresion instead of reference. Angular Select Documentation