我有一个DropDown。我在Option上使用ng-repeat
绑定了它的值。
我想仅使用值字段设置所选值。
这是我的代码。
<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
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";
})
如您所见,我只想设置选定值uisng通过设置值。
答案 0 :(得分:18)
您需要使用ng-model
代替ng-value
将其绑定到模型。
<select ng-model="selectedItemvalue">
更新: $scope.selectedItem
需要在控制器中$scope.selectedItemvalue
,然后您可以使用ng-selected
来匹配条件
工作演示
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>
答案 1 :(得分:5)
您需要为option
代码基本使用以下语法(使用ng-selected
):
<option ng-repeat="sel in selectables" value="{{sel.value}}" ng-selected="sel.value == selectedItemvalue">{{sel.label}}</option>
答案 2 :(得分:0)
如果您尝试
$ scope.selectedItemvalue = {label:'B',value:2};
然后它会起作用。