gpt4 book ai didi

javascript - 在 ng-options 中选择带有条件的默认值

转载 作者:行者123 更新时间:2023-12-02 17:21:46 25 4
gpt4 key购买 nike

我有一个带有以下数组的 Angular 应用程序:

countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}]

使用 Jade 选择如下:

select(ng-model='myCountry', ng-options='country.name for country in countries')

我想做的是根据代码预先选择一个国家/地区,例如:

select(ng-model='myCountry', ng-options='country.name for country in countries', ng-selected='country.code=="CH"')

显然,这个解决方案不起作用,因为 ng-selected 不适合在 select 中使用,而是在选项标签中使用。

对我来说,使用条件选择而不是像 angularJS example 中那样的默认索引值很重要。 。

最佳答案

从上面的示例来看,您应该在 Controller 中执行此操作:

$scope.myCountry = $scope.countries.filter(function(c){ return  c.code==="CH"})[0];

像这样:

<script>
function MyCntrl($scope) {
$scope.countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}];
$scope.myCountry = $scope.countries.filter(function(c){ return c.code==="CH"})[0];
}
</script>

或者您可以尝试使用 和 ngRepeat 构建选择,这似乎更接近您需要的内容,如下所示:

Online Demo

<body ng-app="">
<script>
function MyCntrl($scope) {
$scope.countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}];
}
</script>
<div ng-controller="MyCntrl">
<select ng-model="myCountry" >
<option ng-selected="c.code=='CH'" ng-repeat="c in countries">{{c.name}}</option>
</select><br>
{{myCountry |json}}
</body>

关于javascript - 在 ng-options 中选择带有条件的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876935/

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