gpt4 book ai didi

javascript - AngularJs - SELECT 中的 ng-model

转载 作者:IT王子 更新时间:2023-10-29 02:57:15 26 4
gpt4 key购买 nike

JSfiddle

问题:

我的页面中有一个 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>

使用 JS:

function myCtrl ($scope) {
$scope.units = [
{'id': 10, 'label': 'test1'},
{'id': 27, 'label': 'test2'},
{'id': 39, 'label': 'test3'},
]

$scope.data = {
'id': 1,
'unit': 27
}

};

最佳答案

您可以使用 ng-selected关于选项元素的指令。它需要表达式,如果 truthy 将设置所选属性。

在这种情况下:

<option ng-selected="data.unit == item.id" 
ng-repeat="item in units"
ng-value="item.id">{{item.label}}</option>

演示

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
}

});
<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>

关于javascript - AngularJs - SELECT 中的 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30048605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com