axel
axel

Reputation: 4127

How to avoid empty automatic option in an angularjs select?

<form ng-show="editingUser" class="form-inline editingUser" role="form" name="gebruikerdetailform" novalidate>
<input type="text" class="form-control" ng-model="userDetail.name" placeholder="Naam" ng-required="true"/>
<input type="text" class="form-control" ng-model="userDetail.surname" placeholder="Surname"/>
<select class="form-control" ng-model="userDetail.role">
    <option ng-selected="userDetail.role === 'user' || userDetail.role === ''" >user</option>
    <option ng-selected="userDetail.role === 'admin'">admin</option>
</select>
</form>

in this code, automatically the empty option <option value="? string: ?"></option> is created by angularjs. i know it happens when a value referenced by ng-model doesn't exist in a the ng-options. but this is not the case, and i don't understand how to avoid this behavior, and where does it come from. any ideas?

Upvotes: 1

Views: 343

Answers (1)

Wilk
Wilk

Reputation: 8113

If the problem concerns the initialization of the ng-model, you can use the directive ng-init, as follows:

<form ng-show="editingUser" class="form-inline editingUser" role="form" name="gebruikerdetailform" novalidate>
  <input type="text" class="form-control" ng-model="userDetail.name" placeholder="Naam" ng-required="true"/>
  <input type="text" class="form-control" ng-model="userDetail.surname" placeholder="Surname"/>
  <select class="form-control" ng-model="userDetail.role" ng-init="user">
    <option ng-selected="userDetail.role === 'user' || userDetail.role === ''" >user</option>
    <option ng-selected="userDetail.role === 'admin'">admin</option>
  </select>
</form>

Look at the usage of the ng-init directive in the select definition.

For more info: https://docs.angularjs.org/api/ng/directive/ngInit

Cheers

Upvotes: 2

Related Questions