0

I need to pre-select a specfic element in a Select tag.

My model is this:

{
  user: 'mjones',
  idprofile: 2,
  profiles: [
   {idprofile: 1, profile: 'admin'},
   {idprofile: 2, profile: 'read-write'},
   {idprofile: 3, profile: 'read-only'},
  ]
}

This represents a "user", and I attached a list of profiles to it, before opening a form with user-data, containing a select, for choosing the appropriate profile.

As you can see, the user object doesn't contain a "profile" object, but just it's idprofile. That's the difference between my object and those published in ngSelect documentation.

My view contains the select element as this:

<select class="form-control"
    ng-model="user" 
    ng-options="profile.idprofile for profile in user.profiles">
</select>

This populates the list as expected, but it does not selects the idprofile: 2.

How can I match the idprofile from the user object with one element in the profiles array?, I prefer to work only on the view.

leonardorame
  • 1,131
  • 4
  • 18
  • 35

1 Answers1

2

Your ng-model must be set to user.idprofile and not to the user.

<select class="form-control"
    ng-init="user = user || profile[0]" 
    ng-model="user.idprofile" 
    ng-options="item.idprofile as item.profile for item in user.profiles">
</select>

the ng-options pattern is "select as label for value in array" (https://docs.angularjs.org/api/ng/directive/select)

The code would be easier to read with a few renames:

{
  user: 'mjones',
  idprofile: 2,
  profiles: [
   {id: 1, name: 'admin'},
   {id: 2, name: 'read-write'},
   {id: 3, name: 'read-only'},
  ]
}


<select class="form-control"
    ng-init="user = user || profile[0]" 
    ng-model="user.idprofile" 
    ng-options="profile.id as profile.name for profile in user.profiles">
</select>
apairet
  • 3,162
  • 20
  • 23