ui-select2 multiple init value

887 Views Asked by At

I have a problem to preselect a array of vars for ui-select2 in angular.

My Controller:

$scope.roles= [{"_id":"545e8f2f64f29dc1540f5a88","__v":0,"created":"2014-11-08T21:46:23.553Z","comments":"Administrator Rolle","name":"admin"}];

$scope.userdata.roles = [{"_id":"545e8f2f64f29dc1540f5a88","__v":0,"created":"2014-11-08T21:46:23.553Z","comments":"Administrator Rolle","name":"admin"}];

My View:

<ui-select multiple ng-model="userdata.roles" theme="select2" ng-disabled="disabled" class="input-medium" style="width:100% !important;">
    <ui-select-match placeholder="Wählen Sie ein oder mehrere Rollen...">{{$item.name}}</ui-select-match>
    <ui-select-choices repeat="role in roles | filter:$select.search">
        {{role.name}} ({{role.comments}})
    </ui-select-choices>
</ui-select>

ng-model dont pre-select the value

When I assign the $scope.userdata.roles = $scope.roles It will work.

When it is possible I want to use this arrays, but I was not able to code with this:

$scope.roles= [{"_id":"545e8f2f64f29dc1540f5a88","__v":0,"created":"2014-11-08T21:46:23.553Z","comments":"Administrator Rolle","name":"admin"}];

$scope.userdata.roles = ["admin"];

EDIT: When I use this as my view:

<ui-select multiple ng-model="userdata.roles" theme="select2" ng-disabled="disabled" style="width:100% !important;">
    <ui-select-match placeholder="Bitte wählen Sie eine oder mehrere Rollen...">{{$item.name}} &lt;{{$item.comments}}&gt;</ui-select-match>
    <ui-select-choices repeat="role.name as role in roles">
        <div ng-bind-html="role.name | highlight: $select.search"></div>
        <small>
            {{role.comments}}
        </small>
    </ui-select-choices>
</ui-select>

and this for my controller:

$scope.roles            = [ 
        {
            "_id" : "545e8f2f64f29dc1540f5a88",
            "__v" : 0,
            "created" : "2014-11-08T21:46:23.553Z",
            "comments" : "Administrator Rolle",
            "name" : "admin"
        }
    ];
$scope.userdata.roles = ["admin"];

it will also not work. Is there a problem with the timing?

2

There are 2 best solutions below

1
On

you need to select whole object from array which you want to set as default like

$scope.roles= [{"_id":"545e8f2f64f29dc1540f5a88","__v":0,"created":"2014-11-08T21:46:23.553Z","comments":"Administrator Rolle","name":"admin"}];

$scope.userdata.roles = $scope.roles[0] //set first record as default;
0
On

The key was to add $parant to my ng-model var.