我正在像这样填充我的多项选择:
<select ng-model="myAddress" ng-options="address.addressLines for address in search.result.addresses" >
</select>
目前有 2 件商品。但是当我加载页面时,它似乎添加了一个额外的空白行
<option value="?" selected="selected" label=""></option>
但是当我单击实际的 2 项行时,上述错误行就会消失。知道是什么原因造成的吗?
最佳答案
当选择最初加载到 View 中时,模型 (myAddress) 不是从 Controller 设置的。 Angular 需要一种方式来表示这一点,因此它向选择框添加了一个空选项。一旦做出选择,它就会被填充并摆脱空选项,因为它没有在绑定(bind)到选择的列表中定义。
如果您不希望出现空白选项,则需要在 Controller 中设置一个有效的 $scope.myAddress 以用作默认值。
根据您想要实现的目标,实际上有三种选择。
- 您可以保留它,因为它现在可以正常工作,在做出选择之前有一个空选项可用。
- 在 Controller 中设置一个初始值,这样就没有可用的空选项。
- 始终有一个空选项可用,即使已为选择设置了值。
示例 here :
HTML:
<div ng-app="myApp" ng-controller="MainController">
Select with no value set in controller:<br />
<select ng-model="select1" ng-options="item.name for item in items">
</select> {{select1}}
<br /><br />
Select with value set in controller:<br />
<select ng-model="select2" ng-options="item.name for item in items">
</select> {{select2}}
<br /><br />
Select empty option always available (even after selection):<br />
<select ng-model="select3" ng-options="item.name for item in items">
<option value=""></option>
</select> {{select3}}
</div>
Javascript:
angular.module("myApp", [])
.controller("MainController", function ($scope) {
$scope.items = [
{id: 1, name: "Item 1"},
{id: 2, name: "Item 2"},
{id: 3, name: "Item 3"},
{id: 4, name: "Item 4"}
];
//initial value for select2
$scope.select2 = $scope.items[0];
});
关于javascript - Angular JS 多选选项添加额外的 ?选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27359687/