Angularjs selectedOption 不工作
Angularjs selectedOption not working
我一直在尝试设置select框的默认selected选项,不知道我哪里做错了。
这是我的 html
<span ng-controller="sizeController" style="width:137px; float:left; margin:15px 0 0 10px; ">
<label for="sizeSelect" style="float:left; color:orange">Size:</label>
<select name="sizeSelect" id="colorSelect" style="width:90px" ng-model="size" ng-change ="onSizeChange(size)">
<option ng-repeat="sizeoption in data.sizeOptions" value="{{sizeoption.id}}">{{sizeoption.name }}</option>
</select>
</span>
控制器在这里
function sizeController($scope, $rootScope) {
$scope.data = {
sizeOptions: [
{id: 'Small', name: 'Small'},
{id: 'Medium', name: 'Medium'},
{id: 'Large', name: 'Large'},
{id: 'XLarge', name: 'XLarge'}
],
selectedOption: {id: 'Small', name: 'Small'}
};
$scope.onSizeChange = function(size){
$rootScope.size = size;
};
}
默认情况下,select 框中的第一个值始终为空。
不知道为什么。
提前致谢
我帮你解决。在 angular.
中对 select 使用 ng-option
这里是关于 ng-option
的更多信息:
select 框中的第一个值始终为空,因为它未定义。 select 下拉列表 (ng-model="size"
) 对应模型的 size
属性,最初是 undefined
。将范围内的大小初始化为如下可能的值之一,它将删除未定义的空第一个选项。
$scope.size = 'Medium';
但即使您将大小初始化为第二个或第三个选项,它仍将 select 第一个选项,现在您必须使用 ng-select
到 select 正确的值 ng-selected="size == sizeoption.id"
完整的解决方案here
请使用 ng-options
而不是 ng-repeat
自己选择选项,帮自己一个忙。
<select name="sizeSelect"
id="colorSelect"
style="width:90px"
ng-model="size"
ng-change="onSizeChange(size)"
ng-options="sizeoption.id as sizeoption.name for sizeoption in data.sizeOptions">
</select>
直接设置模型初始化
$scope.size = "Small";
我一直在尝试设置select框的默认selected选项,不知道我哪里做错了。 这是我的 html
<span ng-controller="sizeController" style="width:137px; float:left; margin:15px 0 0 10px; ">
<label for="sizeSelect" style="float:left; color:orange">Size:</label>
<select name="sizeSelect" id="colorSelect" style="width:90px" ng-model="size" ng-change ="onSizeChange(size)">
<option ng-repeat="sizeoption in data.sizeOptions" value="{{sizeoption.id}}">{{sizeoption.name }}</option>
</select>
</span>
控制器在这里
function sizeController($scope, $rootScope) {
$scope.data = {
sizeOptions: [
{id: 'Small', name: 'Small'},
{id: 'Medium', name: 'Medium'},
{id: 'Large', name: 'Large'},
{id: 'XLarge', name: 'XLarge'}
],
selectedOption: {id: 'Small', name: 'Small'}
};
$scope.onSizeChange = function(size){
$rootScope.size = size;
};
}
默认情况下,select 框中的第一个值始终为空。 不知道为什么。 提前致谢
我帮你解决。在 angular.
中对 select 使用ng-option
这里是关于 ng-option
的更多信息:
select 框中的第一个值始终为空,因为它未定义。 select 下拉列表 (ng-model="size"
) 对应模型的 size
属性,最初是 undefined
。将范围内的大小初始化为如下可能的值之一,它将删除未定义的空第一个选项。
$scope.size = 'Medium';
但即使您将大小初始化为第二个或第三个选项,它仍将 select 第一个选项,现在您必须使用 ng-select
到 select 正确的值 ng-selected="size == sizeoption.id"
完整的解决方案here
请使用 ng-options
而不是 ng-repeat
自己选择选项,帮自己一个忙。
<select name="sizeSelect"
id="colorSelect"
style="width:90px"
ng-model="size"
ng-change="onSizeChange(size)"
ng-options="sizeoption.id as sizeoption.name for sizeoption in data.sizeOptions">
</select>
直接设置模型初始化
$scope.size = "Small";