Search code examples
javascriptangularjsng-options

How to select multiple options when preparing a multiple select list in AngularJS


I have the following select list:

<select multiple="multiple" ng-model="userRoles" ng-options="r.id as r.name for r in roles"></select>

The above produces a list of all the available roles. I need to preselect the roles that the user is a member of when presenting the form. I can assign a role to userRoles, but if I try create an array and push the roles associated with the user into that array, none of the items are selected.

I've created a jsBin to let you play with the non-working solution (and hopefully fix it): http://jsbin.com/icoSoj/1/edit?html,js,output

Thanks!


Solution

  • Your selected values are IDs and not full objects.

    As you do r.id as r.name, you need to put IDs into your array and not the full objects.

    http://jsbin.com/uFiDuxa/1/edit