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

Editing Nested Select Options Once Added to Repeated List

我正在尝试创建一个表单来捕获 country/state/city 的嵌套流并推送到 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 中,为每个块创建了一个子作用域,它创建了它自己的 copy/reference ng-model unless 您将点模型用于模型属性(在使用 ng-model 时强烈推荐)。

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

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

而你在 html 你会做 ng-model="selection.city"

这会解决您的一个问题,但您可能仍会面临一些其他问题,因为您正在与主要选择表单共享状态(或者您可能会接受这种行为)。我不确定你想如何 and/or 计划在用户做出选择后更新 "edited" 位置,所以我不想提供更多建议,但拥有table 中的 ng-model 使用 location 中的值(因此 ng-model="location.city"),但随后您还必须更改更新后续下拉值的方式。