![](/img/trans.png)
[英]Select default option in a dropdown, save the value in the value attribute of the dropdown. Angular.js. Angular.js
[英]select default option in dropdown dependent in ANGULAR.JS
我有一個依存下拉列表,我選擇一個國家。 如果選擇了哥倫比亞,則我需要默認標記為“ manizales”,如果選擇了美國(美國),則需要標記“芝加哥”。 我已經嘗試了很多方法,但是不知道如何在第一次標記默認選項。
<select id="country" ng-model="selectedCountry" ng-options="country.id as country.name for country in countries track by country.id">
<option value="">Choose</option>
</select>Departement:
<select id="state"
ng-model="selectedState" ng-options="state.id as state.dep for state in ((countries | filter:{'id':selectedCountry})[0].states) track by state.id">
<option value="">Choose</option>
</select>
也許我不了解我。 我需要一個加載第一個下拉列表的國家,例如哥倫比亞,並且這個國家一旦出現“ manizales”缺陷標記
一種選擇是在國家/地區輸入上使用ng-change
,並在更改時分配$scope.selectedState
。 我還建議向每個國家/地區添加defaultStateId
屬性,以使其更加靈活。
因此,您所在國家/地區的HTML將變為:
<select id="country" ng-change="CountrySelected()" ng-model="selectedCountry" ng-options="country.id as country.name for country in countries track by country.id">
<option value="">Choose</option>
</select>
您的CountrySelected
函數將如下所示:
$scope.CountrySelected = function() {
var countryId = $scope.selectedCountry;
for (var i = 0; i < $scope.countries.length; ++i) {
var country = $scope.countries[i];
if (country.id === countryId) {
$scope.selectedState = country.defaultStateId;
break;
}
}
};
您只需要添加'defaultIndex':每個父元素為0, 此處為示例
var Aplic = angular.module(“ Aplic”,[]);
Aplic.controller('CountryCntrl',function($ scope){
$scope.countries = [{
'id': '1',
'name': "Colombia",
'defaultIndex': 0,
'states': [{
'id': '12',
'dep': "Manizales"
}, {
'id': '11',
'dep': "Bogota"
}]
}, {
'id': '2',
'name': "USA",
'defaultIndex': 1,
'states': [{
'id': '3',
'dep': "California"
}, {
'id': '15',
'dep': "Chicago"
}]
}];
$scope.selectedCountry = $scope.countries[0];
});
您可以使用ng-change
進行以下更改。 http://plnkr.co/edit/RUxVch?p=preview
<select id="country" ng-model="selectedCountry" ng-options="country as country.name for country in countries" ng-change='selectedState = selectedCountry.states[0].id;'>
<option value="">Choose</option>
</select>Departement:
<select id="state"
ng-model="selectedState"
ng-options="state.id as state.dep for state in selectedCountry.states">
<option value="">Choose</option>
</select>
替換ng-model =“ selectedState”
使用以下代碼ng-model =“(countries | filter:{'id':selectedCountry})[0] .states [0]”
您需要做的2件事:
1)將ng-change
添加到selectedCountry
下拉列表中,這會將selectedState
模型設置為列表中的第一個狀態
2)重新排列json中的狀態,以使默認狀態為第一個狀態。
您還可以擴展它以將默認值添加到國家列表或將默認布爾值添加到狀態對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.