gpt4 book ai didi

javascript - Angularjs 触发国家状态依赖

转载 作者:数据小太阳 更新时间:2023-10-29 04:55:59 24 4
gpt4 key购买 nike

有人可以帮助我使我的国家/州下拉依赖示例有效吗?

我有意以这种方式创建 JSON,因为我希望依赖项是通用的,这样我就可以在仅使用元数据而不是 HTML 的情况下将其应用于任何下拉列表。

这是 a link查看 JSFidlle 中的代码示例

HTML

Country:<select data-ng-model="Countries" data-ng-options="country.id as country.name for country in Countries.items">
<option value="">Please select a country</option>
</select>

State: <select data-ng-model="currentItem" data-ng-options="item.id as item.name for item in currentStates.items">
<option value="">Please select a state</option>
</select>

JavaScript 代码:

function Controller($scope) {

var Countries = {
"id": "field10",
"items": [{
"id": "10",
"StateGroupID":"0",
"name": "United State"
},
{
"id": "2",
"StateGroupID":"1",
"name": "Canada"
}]
};

var States =
{ "id": "field20",
"StateGroups": [{
"items": [{ "id": "1",
"name": "Alabama"
},
{
"id": "2",
"name": "Alaska"
},
{ "id": "3",
"name": "Arizona"
},
{ "id": "4",
"name": "California"
}]},

[{ "id": "201",
"name": "Alberta"
},
{
"id": "202",
"name": "British Columbia"
},
{
"id": "303",
"name": "Manitoba"
},
{
"id": "304",
"name": "Ontario"
}]]
};

$scope.Countries = Countries;
$scope.currentStates = States.StateGroups[0];
$scope.$watch('currentStates', function(value, oldValue){
//alert(value);
//alert(JSON.stringify(value));
//$scope.currentStates = (value == "10") ? States.StateGroups[0] : States.StateGroups[1];
});

}

最佳答案

首先,我认为你的 JSON 中有一点错误,你应该在加拿大各州之前有一个“项目”

          {"items": [{  "id": "201",
"name": "Alberta"
}, .....

完成此操作后,我会修改您的 HTML 以便拥有 2 个不同的型号名称(按照您的方式,在第一次点击时您会覆盖国家列表)。然后我将对 ng-repeat 使用不同的语法,以便将值强制为 StateGroupId

 <select data-ng-model="selectedCountry">
<option ng-repeat='country in Countries.items' value='{{country.StateGroupID}}'>{{country.name}}</option>
</select>

这样做可以让您创建一个函数来获取所选组 ID 的状态:

 $scope.getStates=function(){
console.log($scope.selectedCountry)
return $scope.backupStates.StateGroups[$scope.selectedCountry].items;
}

然后你可以使用这个函数使用 ng-repeat 来显示它们

            <select data-ng-model="selectedState" >
<option value="">Please select a state</option>
<option ng-repeat='state in getStates()'>{{state.name}}</option>
</select>

我在这里修改了你的 fiddle :http://jsfiddle.net/DotDotDot/TsxTU/14/ ,我希望这是你想要的那种行为:)

关于javascript - Angularjs 触发国家状态依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18173717/

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