Javascript select中的角度变化导致$scope变量中的奇怪行为
这是我眼中的代码Javascript select中的角度变化导致$scope变量中的奇怪行为,javascript,angularjs,Javascript,Angularjs,这是我眼中的代码 <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="Fra
<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>
这段代码的目的非常简单。如果restaurant.type为“Individual”,则不应设置restaurant\u group。否则,餐厅组应可见且可设置。问题是,餐厅团队似乎没有保持不变
例如。。。我的起始条件是restaurant.type=“Corporate”和restaurant.restaurant_group={“id”:1,“name”:“Something”}。两个选择框都正确显示了这一点。当我为餐馆类型选择“个人”时,餐馆组选择框消失,控制台记录
{}
这就是我所期望的。但是,当我将餐厅类型更改回“公司”时,餐厅组选择框将重新出现,并且已选择“某物”选项。控制台日志立即显示
{“id”:1,“name”:“某物”}
这不是我所期望的。我希望餐厅组保持为空对象,直到我使用餐厅组选择框再次设置它。我显然错过了这里正在发生的一些事情。我预计这会发生,因为
餐厅。餐厅组
绑定到您的div中的餐厅组选择,使用ng if=“restaurant.type='francement'| restaurant.type='Corporate'
因此,当您选择一个新的餐厅类型时,ng if
将解析为true,并且餐厅。餐厅组
将从餐厅组选择
中提取默认值(通常是列表中的顶部).我预计会发生这种情况,因为餐厅.restaurant_group
绑定到您的div中的餐厅组,并使用ng if=“restaurant.type=='特许经营权'| | restaurant.type=='Corporate'
因此,当您选择一个新的餐厅类型时,ng if
将解析为true和餐厅。餐厅组
将从餐厅组选择中获取默认值(通常是列表中的顶部)。您可以为此共享Plnkr吗
这对我有用。请查收
Plunkr
您可以为此共享Plnkr吗
这对我有用。请查收
Plunkr
我认为问题是由于ng if.尝试使用ng show in place ng if我认为问题是由于ng if.尝试使用ng show in place ng if谢谢大家。问题出在我的角度代码之外。我们在后端使用REST服务。角度代码正在将“餐厅”组更改为空对象。然后更新数据并刷新。如果设置为null或空对象,我希望后端删除restaurant_组。相反,它只是忽略了这个属性。因此,在刷新时,后端正在重新填充范围数据
对不起,我浪费了你的时间看这个。事实证明,事情的棱角面是正常的。谢谢大家。问题出在我的角度代码之外。我们在后端使用REST服务。角度代码正在将“餐厅”组更改为空对象。然后更新数据并刷新。如果设置为null或空对象,我希望后端删除restaurant_组。相反,它只是忽略了这个属性。因此,在刷新时,后端正在重新填充范围数据
对不起,我浪费了你的时间看这个。事实证明,事物的角度方面是正常工作的。你能为此创建一个plnkr吗?你能为此创建一个plnkr吗?我想知道使用ng show而不是ng if是否可以避免不想要的行为。我想知道使用ng show而不是ng if是否可以避免不想要的行为。
$scope.restaurantTypeChanged = function() {
if ($scope.restaurant.type == "Individual") {
$scope.restaurant.restaurant_group = {};
}
console.log($scope.restaurant.restaurant_group);
};