使用 ng-repeated 选项指定 Angular ngModel 值
Specifying Angular ngModel Value with ng-repeated options
我有一个 select 下拉菜单,其选项正在从一个名为 $scope.bars
的对象中重复执行。
但是,设置为 $scope.bars
子值的我的 ng-model 没有正确选择选项。相反,select 框默认为空白,表示 'undefined' 值。
这是我的 HTML:
<div ng-app="programApp" ng-controller="programController">
<label>Level:
<select ng-model="advancedFilters">
<option ng-repeat="item in bars" value="item.id">{{item.name}}</option>
</select>
</label>
</div>
这是我的 Angular 代码:
angular.module('programApp', [
'programApp.controllers',
]);
angular.module('programApp.controllers', [])
.controller('programController', ['$scope',
function($scope){
$scope.advancedFilters = 1;
$scope.bars = [
{'name':'First',
'id':1},
{'name':'Second',
'id':2},
{'name':'Third',
'id':3},
{'name':'Fourth',
'id':4},
{'name':'Fifth',
'id':5}];
}]);
因为$scope.advancedFilters
等于1,下拉应该显示'First'选项,因为第一个下拉选项的id值为1。相反,下拉是空白的,说明有问题使用 ng-model.
我该如何解决这个问题?
在这里查看 Codepen:http://codepen.io/trueScript/pen/PqbVyv
如果您对 select 使用 ng-repeat,您将 运行 陷入此类问题。尝试使用 ng-options 代替。即
<select ng-options="item.id as item.name for item in bars"
ng-model="advancedFilters">
</select>
item.id as item.name for item in bars
代表
selectedValue as displayName for item in list
即使您的 ng-model 未定义或不是列表中的项目之一,您也可以通过以下方式设置默认选项:
<select ng-options="item.id as item.name for item in bars"
ng-model="advancedFilters">
<option value="">--Please Select--</option>
</select>
否则,在使用 ng-repeat 时,您需要提供内插值 (value="{{item.id}}"
),即
<option ng-repeat="item in bars"
value="{{item.id}}">{{item.name}}</option>
我有一个 select 下拉菜单,其选项正在从一个名为 $scope.bars
的对象中重复执行。
但是,设置为 $scope.bars
子值的我的 ng-model 没有正确选择选项。相反,select 框默认为空白,表示 'undefined' 值。
这是我的 HTML:
<div ng-app="programApp" ng-controller="programController">
<label>Level:
<select ng-model="advancedFilters">
<option ng-repeat="item in bars" value="item.id">{{item.name}}</option>
</select>
</label>
</div>
这是我的 Angular 代码:
angular.module('programApp', [
'programApp.controllers',
]);
angular.module('programApp.controllers', [])
.controller('programController', ['$scope',
function($scope){
$scope.advancedFilters = 1;
$scope.bars = [
{'name':'First',
'id':1},
{'name':'Second',
'id':2},
{'name':'Third',
'id':3},
{'name':'Fourth',
'id':4},
{'name':'Fifth',
'id':5}];
}]);
因为$scope.advancedFilters
等于1,下拉应该显示'First'选项,因为第一个下拉选项的id值为1。相反,下拉是空白的,说明有问题使用 ng-model.
我该如何解决这个问题?
在这里查看 Codepen:http://codepen.io/trueScript/pen/PqbVyv
如果您对 select 使用 ng-repeat,您将 运行 陷入此类问题。尝试使用 ng-options 代替。即
<select ng-options="item.id as item.name for item in bars"
ng-model="advancedFilters">
</select>
item.id as item.name for item in bars
代表
selectedValue as displayName for item in list
即使您的 ng-model 未定义或不是列表中的项目之一,您也可以通过以下方式设置默认选项:
<select ng-options="item.id as item.name for item in bars"
ng-model="advancedFilters">
<option value="">--Please Select--</option>
</select>
否则,在使用 ng-repeat 时,您需要提供内插值 (value="{{item.id}}"
),即
<option ng-repeat="item in bars"
value="{{item.id}}">{{item.name}}</option>