javascript 使用angularjs为下拉列表设置默认值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19916967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set default value for dropdownlist using angularjs?
提问by punkouter
I have code that populates then dropdownlist and the javascript variable that gets the last item in the list. Now all I want to do is select that last item as the default .What am I missing ?
我有代码,然后填充下拉列表和获取列表中最后一项的 javascript 变量。现在我想要做的就是选择最后一项作为默认值。我错过了什么?
<div class="row">
<div>
<select ng-init="lastItem" ng-model="congressFilter" ng-options="cc.congressLongName for cc in ccList"></select>
</div>
<div class="grid-style" data-ng-grid="userGrid">
</div>
ccResource.query(function (data) {
$scope.ccList.length = 0;
angular.forEach(data, function (ccData) {
$scope.ccList.push(ccData);
})
//Set default value for dropdownlist?
$scope.lastItem = $scope.ccList[$scope.ccList.length - 1];
});
回答by hugo der hungrige
You simply need to asign a value to congressFilter in your controller.
您只需要在您的控制器中为 CongressFilter 分配一个值。
$scope.congressFilter = 'someVal';
It depends a little on how your data looks however.
然而,这在一定程度上取决于您的数据的外观。
回答by Anil Singh
It might help to new developers. need to add default id for display default item in option.
它可能对新开发人员有所帮助。需要在选项中添加默认 id 以显示默认项目。
The below code sample we add [ $scope.country.stateid = "4" ] in controller $scope to set the default.
下面的代码示例我们在控制器 $scope 中添加 [ $scope.country.stateid = "4" ] 以设置默认值。
var aap = angular.module("myApp", []);
aap.controller("MyContl", function($scope) {
$scope.country = {};
$scope.country.stateid = "4";
$scope.country.states = [{
id: "1",
name: "UP"
}, {
id: "4",
name: "Delhi"
}];
});
<body ng-app="myApp">
<div ng-controller="MyContl">
<div>
<select ng-model="country.stateid" ng-options="st.id as st.name for st in country.states">
</select>
ID : {{country.stateid}}
</div>
</div>
</body>