Select multiple objects and save to ng-model

2019-05-25 04:35发布



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

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

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 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

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'}];

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



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