gpt4 book ai didi

javascript - 如何在 ng-repeat 中为多个选择填充动态选项

转载 作者:行者123 更新时间:2023-11-30 19:19:53 25 4
gpt4 key购买 nike

我通过单击 Html 表单中的“添加行”按钮来添加动态行。在一行中,我选择了“国家”和“州”。每当我选择国家/地区时,如果我更改国家/地区,则第一行和第二行中的州会正确填充所有其他行值也会发生变化。请帮忙。在下面的代码中,“data.states”数组,我从数据库加载。但问题出在多行之间,states array is getting overrided for each country change.

 <table>
<tr>
<th>Country</th>
<th>State</state>
<th>Action</th>
</tr>
<tr ng-repeat="model in models track by $index">
<td>
<select ng-options="country in countries" ng-model="country" ng-change='getState(country)'>
</select>
</td>
<td>
<select ng-options="state in data.states">
</select>
</td>
<td><button ng-click="addRow()">Add Row</button></td>
</tr>
</table>

$scope.models = [{}];

$scope.addRow = function(){
$scope.models.push({});
}

最佳答案

问题是您的所有代码都对国家/地区使用相同的 ng-model 引用,而且您没有在范围内使用不同的变量来在此处为每个国家/地区存储您的州:<select ng-options="state in data.states"></select>

试试下面的代码

    <table>
<tr>
<th>Country</th>
<th>State</th>
<th>Action</th>
</tr>
<tr ng-repeat="model in models">
<td>
<select ng-options="country as country for country in countries" ng-model="model.country" ng-change='getState(model.country)'>
</select>
</td>
<td>
<select ng-options="state as state for state in getState(model.country)" ng-model="model.state">
</select>
</td>
<td><button ng-click="addRow()">Add Row</button></td>
</tr>
</table>


$scope.models = [{}];

$scope.countries = ['Brazil', 'Canada', 'US'];

$scope.states = {
Brazil: ['Rio de Janeiro', 'Acre', 'Bahia'],
Canada: ['Ontario', 'Alberta', 'Manitoba'],
US: ['California', 'Florida', 'Texas'],
}

$scope.addRow = function(){
$scope.models.push({});
}

$scope.getState = function(country){
// implement your fetch state logic here
return $scope.states[country];
}

这是一个有效的 plunker:https://plnkr.co/edit/coh5niQXon10l5RHYKza?p=info

关于javascript - 如何在 ng-repeat 中为多个选择填充动态选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57595157/

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