我有以下列出国家及其状态的JSON文件:
[
{
"value": "Australia",
"text": "Australia",
"states": [
{
"value": "Australian Capital Territory",
"text": "Australian Capital Territory"
},
{
"value": "New South Wales",
"text": "New South Wales"
}
]
}
]
我将数据加载到名为countriesAndStates的变量中,然后在前端显示:
<div class="form-group">
<label for="country" class="col-sm-2 control-label">Country</label>
<div class="col-sm-3">
<select class="form-control" id="country" data-ng-model="project.country" data-ng-options="country.value as country.text for country in countriesAndStates">
<option disabled value="">Select</option>
</select>
</div>
</div>
<div class="form-group">
<label for="country" class="col-sm-2 control-label">State</label>
<div class="col-sm-3">
<select class="form-control" id="state" data-ng-model="project.state" data-ng-options="state.value as state.text for state in countriesAndStates.states" data-ng-disabled="!countriesAndStates.states">
<option disabled value="">Select</option>
</select>
</div>
</div>
我还从REST API加载数据以在前端显示它:
var detailProject = Restangular.one('projects', $routeParams.projectId);
detailProject.get().then(function (project) {
$scope.project = project;
$scope.saveProject = function () {
project.put().then(processSuccess, processError);
};
});
单击“保存”后,saveProject函数会将数据放回API。
现在......我如何将国家与国家联系起来?
根据我在文档中的理解,我需要更改ng-model属性以反映国家和州......就像这样:
<select id="country" ng-model="states" ng-options=""></select>
<select id="state" ng-disabled="!states" ng-options=""></select>
但是我有点困惑,当我希望在选择框中加载API数据时,我该怎么做呢?
答案 0 :(得分:1)
我觉得这样的事情会起作用......
您可以按project.country
过滤选项。我还放置了一个禁用ng指令,以防止他们在此下拉列表中选择一个选项,如果他们尚未首先选择一个国家/地区。
<select ng-disabled="!project.country" ng-model="selectedState"
ng-options="state.value as state.text for state in countriesAndStates.states | filter:{text: project.country}"></select>
答案 1 :(得分:1)
搜索了几个小时......我终于明白了。为可能遇到同样问题的每个人发布此信息。
我修改了我的数据,将国家/地区分为两个不同的文件
<强>国家:强>
[
{ "name": "United States" },
{ "name": "Canada" }
etc...
]
的国:强>
[
{ "name": "Alabama", "country": "United States" },
{ "name": "Alberta", "country": "Canada" }
etc...
]
修改后的HTML
<select data-ng-model="project.country" data-ng-options="country.name as country.name for country in countries" data-ng-change="updateCountry()" class="form-control">
<option disabled value="">Select country</option>
</select>
<select data-ng-disabled="!project.country" data-ng-model="project.province" data-ng-options="state.name as state.name for state in states | filter:{country: availableStates}" class="form-control">
<option disabled value="">Select state</option>
</select>
<强>控制器强>
$scope.updateCountry = function () {
$scope.availableStates = $scope.project.country; // filter by country
$scope.project.province = ''; // reset the province field to empty
};