2

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":"[email protected]","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?

0

4 Answers 4

3

Okay, I have found the solution. If anybody can suggest better solution, please post it

function to check if role exists in the given array of roles

$scope.isRoleContains = function(roles, roleToFind) {
    var is = false;
    angular.forEach(roles, function(role) {
        if (role.name == roleToFind.name)
            is = true;
    });
    return is;
}

updated select box

<select ng-model="user.roles" multiple="multiple">
    <option ng-repeat="role in roles" ng-selected="isRoleContains(user.roles, role)">
        {{ role.name }}
    </option>
</select>
Sign up to request clarification or add additional context in comments.

Comments

1

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

1

I think the only issue is that roles should not contain anything but the key.

"roles":[{"id":2}]

Here is how you use multi-select: http://jsfiddle.net/vYaNx/3/

You need to have what is selected in your data. User.roles should be the selected data.

HTML:

<select multiple ng:model="selectedColors" ng:options="k as v for (k, v) in colors"></select>

Javascript:

$scope.colors = {
    b: 'black',
    w: 'white',
    r: 'red',
    c: 'cyan',
    y: 'yellow'
  };
  $scope.selectedColors = ['r', 'c'];

1 Comment

sorry, this looks like standard answer, I didnt find answer on my question
0

H i, Throwing this in to the mix :

DEMO: http://jsfiddle.net/rq2ky/1/

key being the setup of the ng-options ( declaring what the key values are )

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.