[英]Select default value with condition in ng-options
我有一個帶有以下數組的角度應用程序:
countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}]
與玉選擇如下:
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中使用,而是在option標簽中使用。
對於我來說,重要的是使用條件選擇而不是像angularJS示例中那樣使用默認索引值。
那就是ng-model的目的。 我建議您在控制器中初始化myCountry。 請注意,理想情況下,myCountry應該與國家/地區具有相同的格式(例如: {"code": "ZA", "name": "South Africa"}
)。
編輯:我要從我自己的項目中添加一個示例:
<select class="small" data-ng-change="goToTask(current_task.id)" data-ng-model="current_task" data-ng-options="task.name for task in tasks track by task.id"></select>
在控制器中:
$scope.current_task = { id: $scope.myService.getCurrentTaskId() };
這里重要的是current_task至少是包含id
鍵的哈希。
Edit2:我正在考慮跟蹤依據的排序問題。 我認為您可以使用select
代替,例如:“ ng-options =“選擇country.code作為國家/地區中國家/地區的國家/地區名稱”。 我沒有嘗試過,但是從有角度的文檔中,它應該可以工作。
從上面的示例中,您似乎應該在控制器中執行此操作:
$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
和ngRepeat
構建選擇,這似乎更接近您的需求,例如:
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.