[英]Use of ng-option
在這里,我創建了一個包含國家/地區的數組,當我選擇一個特定國家/地區時,他們的國家/地區列表應顯示在另一個選擇選項卡中。 我怎樣才能做到這一點
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="item for item in names">
</select>
{{selectedName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["India", "US", "UK"];
});
</script>
</body>
</html>
我會給你一個正確方向的提示,他們有很多方法可以做到這一點,這遠不是一個現實世界的例子。
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="item for item in names" ng-change="countrySelected()"></select>
{{selectedName}}
<select ng-model="selectedState" ng-options="item for item in states"></select>
{{selectedState}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["India", "US", "UK"];
$scope.states = [];
$scope.countrySelected = function () {
if ($scope.selectedName == "India") {
$scope.states = ["Some", "State"];
}
}
});
</script>
通常,您會有來自后端的結構化數據,例如:
[{ country:"US", states: ["One", "Two"]}]
選擇一個國家后,應在另一個選擇框中使用這些州。 此外,一些 ID 將來自您的后端,因此您可以在完成后將所選的 countryID 和 stateID 發送到服務器。
請注意,鑒於信息有限,這只是眾多解決方案之一。 假設您有每個國家/地區集合的州列表:
//For example
$scope.listOfStatesPerCountry = {
country: {
name: 'India',
states: ['Northern-India', 'Southern-India']
}
country: {
name: 'US',
states: ['Alabama', 'Kentucky', 'California']
}
}
$scope.getStatesForCountry = function() {
if($scope.selectedCountry) {
return $scope.listOfStatesPerCountry[$scope.selectedCountry];
}
return [];
}
相應的 HTML
<select ng-model="selectedCountry" ng-options="country for country in listOfStatesPerCountry">
</select>
<select ng-options="state for state in getStatesForCountry()"></select>
這是您查詢的解決方案。首先,您需要在國家/地區的值發生變化時點擊該功能。 然后比較它的值並獲得狀態。 測試代碼..
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-change="selectstate(selectedName)" ng-options="item for item in names">
</select>
<div ng-if='states'>
<select ng-model="selectedState" ng-options="item for item in states">
</select></div>
{{states}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["India", "UK", "US"];
$scope.selectstate = function(value){
if(value=='India'){
$scope.states = ["Chandigarh", "Punjab", "Bihar"];
}else if(value=='UK'){
$scope.states = ["fg", "jg", "fh"];
}else if(value=='US'){
$scope.states = ["fhgfj", "gjffg", "gfjjfg"];
}else{
//do nothing
}
alert(value)
}
});
</script>
<p>This example shows how to fill a dropdown list using the ng-options directive.</p>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.