如何避免angularjs选择中的空自动选项?

时间:2014-06-17 07:56:23

标签: javascript html5 angularjs

<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>

在此代码中,自动为angularjs创建空选项<option value="? string: ?"></option>。我知道当 ng-options 中不存在 ng-model 引用的值时会发生这种情况。 但事实并非如此,我不明白如何避免这种行为,以及它来自何处。 任何想法?

1 个答案:

答案 0 :(得分:2)

如果问题涉及 ng-model 的初始化,您可以使用指令ng-init,如下所示:

<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>

查看选择定义中ng-init指令的用法。

了解更多信息:https://docs.angularjs.org/api/ng/directive/ngInit

干杯