javascript - 选择中的 Angular 变化导致 $scope 变量出现奇怪的行为

标签 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="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_grouprestaurant- 获取默认值group-select(通常是列表中的顶部)。

关于javascript - 选择中的 Angular 变化导致 $scope 变量出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32715250/

相关文章:

angularjs - 确定表 header value 是它们应该的值

javascript - 如何从指令链接方法中调用 js 插件 - Angularjs

javascript - HTML5 拖放占位符在离开时将parentNode 设置为 null (js vanilla)

javascript - 在JavaScript中保存日期 'without'时间

javascript - 旋转 8x8 位矩阵的高效 JavaScript 方法,由 8 个十六进制值表示

angularjs - Angular 中的 this.model 指令内部

javascript - 鸭子类型(duck typing)用 JSON 对象打字 - 尝试/除外?

javascript - 无法像 NPM 包一样捆绑要导入的 Web Worker

javascript - 如何获取 JSON 对象到 React 组件?

ruby-on-rails - 从 Rails 的 JSON 响应中寻找用于在 Angular 中进行通用错误处理的范例