添加到重复列表后编辑嵌套选择选项



我正在尝试创建一个表单,该表单捕获国家/州/城市的嵌套流,并将其推送到ng repeat对象。一旦它被添加到中继器中,我希望可以选择编辑嵌套的选择。

我不明白一旦一个嵌套对象被添加到中继器中,ngModel和ngOptions是如何发挥作用的。我试过几种选择都没有成功。

我添加了一个plunker来帮助解释这个问题:http://next.plnkr.co/edit/FWLa3ErI83JLR4Jy

这是有问题的部分,工作不正常:

HTML

<tr ng-repeat="location in locations">
<td>
<select ng-show="editable" name='CountryName' id="CountryName" class="form-control" ng-model="country" ng-options="country as country.CountryName for country in countries"
required>
<option value="" disabled>Select</option>
</select>
<span ng-show="!editable">{{location.CountryName}}</span>
</td>
<td>
<select ng-show="editable" name='StateName' required id="StateName" class="form-control" ng-disabled="states.length == 0" ng-model="state" ng-options="state as state.StateName for state in states">
<option value="" disabled>Select</option>
</select>
<span ng-show="!editable">{{location.StateName}}</span>
</td>
<td>
<select ng-show="editable" name='CityName' required id="CityName" class="form-control" ng-disabled="cities.length == 0" ng-model="city" ng-options="city as city.CityName for city in cities">
<option value="" disabled>Select</option>
</select>
<span ng-show="!editable">{{location.CityName}}</span>
</td>
<td><a class="btn btn-link" ng-click="editable = !editable">Edit</a></td>
</tr>

JS-

$scope.recordLocation = function() {
$scope.locations.unshift({
CountryName: $scope.country.CountryName,
StateName: $scope.state.StateName,
CityName: $scope.city.CityName
});
$scope.city = {};
$scope.state = {};
$scope.country = [];
};

寻求有关如何解决此问题的帮助。

感谢

您的对象的范围本质上存在问题。(点击此处阅读更多信息:https://docs.angularjs.org/guide/scope)

在ng repeat中,每个块都会创建一个子作用域,该子作用域会创建ng-model中指定的变量的自己的副本/引用,除非对模型属性使用点模型(使用ng模型时强烈建议使用点模型(。

例如,您不应该在html中使用$scope.city = ...ng-model="city",而应该执行以下操作:

$scope.selection = {
city: "",
state: "",
country: ""
}

和你的html你会做ng-model="selection.city"

这将解决你的一个问题,但你可能仍然会面临一些其他问题,因为你正在与主选择表单共享状态(或者你可能会接受这种行为(。我不确定在用户做出选择后,你想和/或计划如何更新"编辑"的位置,所以我不想给出更多建议,但让表中的ng模型使用location中的值(因此是ng-model="location.city"(可能是有意义的,但你也必须更改更新后续下拉值的方式。

最新更新