pleerock pleerock - 3 months ago 11
Javascript Question

AngularJS - multiselect options when model and options are different

I have multiple select box for user to select his roles.

<select ng-options="role.name for role in roles"
ng-model="user.roles"
multiple="multiple">
</select>


"roles" - is the list of roles that user can select

[{"id":1,"name":"Moderator"},{"id":2,"name":"Admin"}]


"user.roles" - list of roles that user actually have

{"id":5,"email":"la@la.la","roles":[{"id":2,"name":"Admin"}]}


Both "roles" and "user" are loading dynamically via ajax.
The problem is that when I load user that already have roles - they are not automatically selected in the select box. How do I select them?

Answer

What is your version of angular ?

In angular 1.0.X, angular check if items are strictly equals (so roles must be the same instance in ng-model and selected item in array).

If you use a more recent version of angular (1.2.x), you can use 'track by' in your ng-option:

<select
    ng-options="role.name for role in roles track by role.name"
    ng-model="user.roles"
    multiple>
</select>

See this fiddle: http://jsfiddle.net/qJLwp/2

Comments