Jor*_*mus 55 javascript jquery angularjs angular-ngmodel
问题:
我的页面中有一个SELECT元素,用一个填充ng-repeat.它还有ng-model一个默认值.
当我改变值时,ng-model适应,这没关系.但是下拉列表在启动时显示一个空槽,它应该具有选择默认值的项目.
码
<div ng-app ng-controller="myCtrl">
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
<option ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
</select>
</div>
Run Code Online (Sandbox Code Playgroud)
用JS:
function myCtrl ($scope) {
$scope.units = [
{'id': 10, 'label': 'test1'},
{'id': 27, 'label': 'test2'},
{'id': 39, 'label': 'test3'},
]
$scope.data = {
'id': 1,
'unit': 27
}
};
Run Code Online (Sandbox Code Playgroud)
Pat*_*ans 69
您可以在选项元素上使用ng-selected指令.需要表达的是,如果truthy将设置所选属性.
在这种情况下:
<option ng-selected="data.unit == item.id"
ng-repeat="item in units"
ng-value="item.id">{{item.label}}</option>
Run Code Online (Sandbox Code Playgroud)
演示
angular.module("app",[]).controller("myCtrl",function($scope) {
$scope.units = [
{'id': 10, 'label': 'test1'},
{'id': 27, 'label': 'test2'},
{'id': 39, 'label': 'test3'},
]
$scope.data = {
'id': 1,
'unit': 27
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
<option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
</select>
</div>Run Code Online (Sandbox Code Playgroud)
car*_*ton 17
尝试以下代码:
在你的控制器中:
function myCtrl ($scope) {
$scope.units = [
{'id': 10, 'label': 'test1'},
{'id': 27, 'label': 'test2'},
{'id': 39, 'label': 'test3'},
];
$scope.data= $scope.units[0]; // Set by default the value "test1"
};
Run Code Online (Sandbox Code Playgroud)
在您的页面中:
<select ng-model="data" ng-options="opt as opt.label for opt in units ">
</select>
Run Code Online (Sandbox Code Playgroud)
您不需要定义选项标记,您可以使用ngOptions指令执行此操作:https://docs.angularjs.org/api/ng/directive/ngOptions
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
126659 次 |
| 最近记录: |