You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS1下拉框问题求助:选中已有选项时出现重复显示

解决AngularJS下拉框选中已有选项时重复显示的问题

嘿,我完全懂你遇到的这个坑!问题出在那个单独加的<option ng-if="newItem.Manufacturer">上——当你选中下拉框里已有的选项时,newItem.Manufacturer会被设置为该选项的值,这时候ng-if的条件就满足了,会在下拉框顶部再生成一个一模一样的选项,所以才会出现重复显示的情况。

问题根源拆解

你原本的逻辑是想用那个单独的option显示新增的内容,但忽略了:选中已有选项时,newItem.Manufacturer的值也会匹配这个option的显示条件,导致它和ng-repeat渲染的选项重复出现。

正确的解决方案

我们应该把新增的内容直接加入到addNewCategory数组中,让ng-repeat(或更推荐的ng-options)统一渲染所有选项,这样就不会有重复的问题了。

1. 修改HTML代码

移除那个单独的ng-if选项,统一用ng-repeat或ng-options渲染所有选项,同时添加输入框和添加按钮的逻辑:

<!-- 新增输入框和添加按钮 -->
<input type="text" ng-model="tempManufacturer" placeholder="输入新分类名称">
<button ng-click="addNewManufacturer()" class="btn btn-primary">添加并选中</button>

<!-- 优化后的下拉框 -->
<select ng-model="newItem.Manufacturer" style="font-size: 15px; padding: 0px 25px;" class="form-control">
    <option value="">--Select Category--</option>
    <!-- 用track by避免重复渲染问题 -->
    <option ng-repeat="category in addNewCategory track by category.Manufacturer" 
            value="{{category.Manufacturer}}">
        {{category.Manufacturer | camelCase }}
    </option>
</select>

2. 完善Controller逻辑

在controller里添加新增分类的方法,确保新增内容被加入数组,同时自动选中:

// 初始化数据
$scope.addNewCategory = [];
// 假设$scope.items是你的原始数据源,去重后赋值
$scope.addNewCategory = $scope.items.unique('Manufacturer');
// 临时存储输入的新分类名称
$scope.tempManufacturer = '';
// 初始化newItem
$scope.newItem = { Manufacturer: '' };

// 添加新分类的方法
$scope.addNewManufacturer = function() {
    if (!$scope.tempManufacturer.trim()) return; // 空值不处理

    // 检查分类是否已存在,避免重复添加
    const isExist = $scope.addNewCategory.some(item => item.Manufacturer === $scope.tempManufacturer);
    if (!isExist) {
        $scope.addNewCategory.push({ Manufacturer: $scope.tempManufacturer });
    }

    // 设置刚添加的分类为选中状态
    $scope.newItem.Manufacturer = $scope.tempManufacturer;
    // 清空输入框
    $scope.tempManufacturer = '';
};

3. 进阶优化:使用ng-options(更推荐)

AngularJS的ng-options专门用于处理select下拉框,比ng-repeat更高效,写法也更简洁:

<select ng-model="newItem.Manufacturer" style="font-size: 15px; padding: 0px 25px;" class="form-control"
        ng-options="category.Manufacturer as (category.Manufacturer | camelCase) for category in addNewCategory">
    <option value="">--Select Category--</option>
</select>

这种写法不需要手动处理value绑定,也能避免很多ng-repeat带来的小问题。

这样修改后,不管是新增分类还是选中已有分类,下拉框里的选项都是统一渲染的,再也不会出现重复显示的情况啦!

内容的提问来源于stack exchange,提问作者Bhargavi Abhirami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:36:07