Javascript 无法在angularJs中设置DropDown的选定值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28169596/
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
Unable to Set Selected Value Of DropDown In angularJs
提问by Amit Kumar
I have a DropDown. I'm binding it's value using ng-repeaton Option.
I want to Set the selected value using the value field only .
我有一个下拉菜单。我正在使用ng-repeatOption绑定它的值。我只想使用值字段设置选定的值。
This is My code.
这是我的代码。
<div ng-controller="myCtrl">
<select ng-model="selectedItemvalue">
<option value="">--Select --</option>
<option ng-repeat="sel in selectables" value="{{sel.value}}">{{sel.label}}</option>
</select>
<p>Selected Value is : {{selectedItemvalue}}</p>
</div>
Js
JS
angular.module('myApp', [])
// controller here
.controller('myCtrl', function($scope) {
$scope.selectables = [
{ label: 'A', value: 1},
{ label:'B', value: 2},
{ label: 'C', value: 3}
];
// this is the model that's used for the data binding in the select directive
// the default selected item
//using value, i want to set the selected value
$scope.selectedItemvalue = "2";
})
As you can see, I want to set selected value uisng only By setting Value.
如您所见,我只想通过设置值来设置选定的值。
回答by A.B
You need to use ng-modelinstead of ng-valueto bind it to model.
您需要使用ng-model而不是将ng-value其绑定到模型。
<select ng-model="selectedItemvalue">
Update:$scope.selectedItemneeds to be $scope.selectedItemvaluein controller and then you can use ng-selectedto match condition on it
更新:$scope.selectedItem需要$scope.selectedItemvalue在控制器中,然后您可以使用ng-selected它来匹配条件
Working Demo
工作演示
angular
.module('myApp', [])
// controller here
.controller('myCtrl', function($scope) {
$scope.selectables = [
{ label: 'A', value: 1},
{ label:'B', value: 2},
{ label: 'C', value: 3}
];
// this is the model that's used for the data binding in the select directive
// the default selected item
//using value, i want to set the selected value
$scope.selectedItemvalue = "2";
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-controller="myCtrl" ng-app="myApp">
<select ng-model="selectedItemvalue">
<option value="">--Select --</option>
<option ng-repeat="sel in selectables" ng-selected="selectedItemvalue == sel.value" value="{{sel.value}}">{{sel.label}}</option>
</select>
<p>Selected Value is : {{selectedItemvalue}}</p>
</div>
回答by Shashank Agrawal
You need to basically use the following syntax for your optiontag (use ng-selected):
您基本上需要为您的option标签使用以下语法(使用ng-selected):
<option ng-repeat="sel in selectables" value="{{sel.value}}" ng-selected="sel.value == selectedItemvalue">{{sel.label}}</option>
回答by Ankit Gupta
If you try
如果你试试
$scope.selectedItemvalue = { label:'B', value: 2};
$scope.selectedItemvalue = { label:'B', value: 2};
then it will work.
然后它会起作用。

