这是我认为的代码...
<label for="restaurant-type-select" class="control-label">
Type
</label>
<select class="form-control" id="restaurant-type-select" ng-model="restaurant.type" ng-change="restaurantTypeChanged()">
<option value="Franchise">Franchise</option>
<option value="Corporate">Corporate</option>
<option value="Individual">Individual</option>
</select>
<div ng-if="restaurant.type == 'Franchise' || restaurant.type == 'Corporate'">
<label for="restaurant-group-select" class="control-label">
Restaurant Group
</label>
<select class="form-control" id="restaurant-group-select" ng-model="restaurant.restaurant_group" ng-options="restaurant_group.name for restaurant_group in restaurant_groups.items track by restaurant_group.id">
</select>
</div>
这是相关的 Controller 代码...
$scope.restaurantTypeChanged = function() {
if ($scope.restaurant.type == "Individual") {
$scope.restaurant.restaurant_group = {};
}
console.log($scope.restaurant.restaurant_group);
};
这段代码的目的非常简单。如果 restaurant.type 是“Individual”,则不应设置 restaurant_group。否则,restaurant_group 应该可见且可设置。问题是 restaurant_group 似乎没有保持不变。
例如...我的起始条件是 restaurant.type = "Corporate"和 restaurant.restaurant_group = { "id": 1, "name": "Something"}。两个选择框都正确显示了这一点。当我为餐厅类型选择“个人”时,餐厅组选择框消失,控制台记录...
{}
这是我所期望的。但是,当我将餐厅类型改回“公司”时,餐厅组选择框再次出现,其中“某事”选项已被选中。控制台日志立即显示...
{"id": 1, "name": "Something"}
这不是我所期望的。我希望餐厅组保持为空对象,直到我使用餐厅组选择框再次设置它。我显然错过了这里发生的事情。
最佳答案
我预计会发生这种情况,因为 restaurant.restaurant_group
使用 ng-if="restaurant.type"绑定(bind)到您的 div 中的
。restaurant-group-select
== '特许经营' || restaurant.type == '公司'”
因此,当您选择新的餐厅类型时,ng-if
解析为 true 并且 restaurant.restaurant_group
从 restaurant- 获取默认值group-select
(通常是列表中的顶部)。
关于javascript - 选择中的 Angular 变化导致 $scope 变量出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32715250/