Search code examples
angularjsng-optionsangularjs-ng-options

ng-options not selecting last item in option array


I have a weird problem that I'm not able to reproduce on Plunker. When the first option 'user' is set in the model, the select displays it properly and it is set to 'user'. When I load another user with role:'admin', the select is set to blank option.

In my controller I define:

$scope.roles = ['user', 'admin'];

My $scope.user object looks like this:

{
   "_id": "54f1f8f7e01249f0061c5088",
   "displayName": "Test1 User",
   "provider": "local",
   "username": "test1",
   "__v": 0,
   "updated": "2015-03-02T07:41:42.388Z",
   "created": "2015-02-28T17:20:55.893Z",
   "role": "admin",
   "profileImageURL": "modules/users/img/profile/default.png",
   "email": "[email protected]",
   "lastName": "User",
   "firstName": "Test1"
}

In my view:

<select id="role" class="form-control" data-ng-model="user.role" data-ng-options="role for role in roles"></select>

When I reverse the roles array $scope.roles = ['admin', 'user']; then admins are displayed properly, and 'user' won't be set as selected.

Strangely if I add a third item to the array $scope.roles = ['user', 'admin', 'joe']; Then the first two 'user' and 'admin' will be set selected properly, and the last one 'joe' won't.

Any ideas?

--- UPDATE ---

The generated select markup looks like this:

<select id="role" class="form-control ng-pristine ng-valid" data-ng-options="role for role in roles" data-ng-model="user.role">
    <option value="? string:joe ?"></option>
    <option value="0" selected="selected" label="admin">admin</option>
    <option value="1" label="user">user</option>
    <option value="2" label="joe">joe</option>
</select>

Solution

  • I made all combinations with you suggest, but the error doesn't occur.

    Please look for my tests:

    http://plnkr.co/edit/jzfhD3D60fhj8yFqBqgJ?p=preview

    <h3>select</h3>
    <select ng-model="role" ng-options="item for item in roles"></select>
    <h3>original</h3>
    <select id="role" class="form-control" data-ng-model="user.role" data-ng-options="role for role in roles"></select>
    

    Try to verify your angularjs version. Maybe can be a specific version error.