AngularJS - 在选择标签中使用 ng-repeat 添加额外的空白选项 [英] AngularJS - extra blank option added using ng-repeat in select tag
问题描述
我有一个使用 AngularJS ng-repeat 的选择创建的列表框.列表框已正确创建,当我选择其中一项并单击我的按钮时,我会进入该功能并获得我需要的信息.
I have a listbox that I am creating with a select, using AngularJS ng-repeat. The listbox is created correctly, and when I select one of the items and click my button, I get to the function and have the information I need.
我的html代码如下:
My html code is as follows:
<select size="6" ng-model="item" ng-options="s.name for s in itemlist"></select>
<button class="btn tt-btn-blue" ng-model="singleModel" ng-click="onLoadClicked(item.id)">Load</button>
我的问题是,当列表框绘制时,它的顶部有一项是空白的.当我在 Chrome 中运行期间检查列表框时,我在控制台中得到以下输出:
My problem is that when the listbox paints, it has one item at the top that is blank. When I inspect the listbox during a run in Chrome, I get the following output in the console:
<select size="6" ng-model="item" ng-options="s.name for s in itemlist" class="ng-pristine ng-valid">
<option value="?" selected="selected"></option>
<option value="0">Item 1</option>
<option value="1">Item 2</option>
<option value="2">Item 3</option>
<option value="3">Item 4</option>
<option value="4">Item 5</option>
<option value="5">Item 6</option>
</select>
我想知道如何摆脱 ng-repeat 插入的第一个选项.我不想在列表框顶部看到空白区域.我意识到一个选项是将第一个实际选项 (value="0") 设置为所选项目,但我宁愿没有选择项目.
I am wondering how I can get rid of the first option inserted by the ng-repeat. I don't want to see a blank space at the top of the listbox. I realize one option would be to set the first actual option (value="0") as the selected item, but I would rather have no selected items to start.
推荐答案
任何时候看到
Any time you see <option value="?" selected="selected"></option>
in the select, it means that your ng-model
is set to a value that isn't in the ng-options
. So, if you don't want the blank option, you need to make sure item
is set to a value in your itemlist
. This could be as easy as having the following in your controller:
$scope.item = $scope.itemlist[0];
这会给它一个初始值,然后 angular 会为你更新它.
This will give it an inital value, and then angular will update it for you thereafter.
这篇关于AngularJS - 在选择标签中使用 ng-repeat 添加额外的空白选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!