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

Angular1+Bootstrap3实现带复选框的多选下拉及取值方法

AngularJS + Bootstrap3 带复选框的多选下拉实现方案

前置准备

因为你是手动引入文件,确保HTML头部已加载以下资源(版本可根据项目实际调整):

<link rel="stylesheet" href="path/to/bootstrap.min.css">
<script src="path/to/angular.min.js"></script>
<script src="path/to/bootstrap.min.js"></script>

完整实现代码

HTML结构

<div ng-app="multiSelectApp" ng-controller="GroupSelectCtrl">
  <!-- 多选下拉触发器 -->
  <div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
      {{getSelectedLabel()}} <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu">
      <li role="presentation" ng-repeat="group in groups">
        <div role="menuitem" style="padding: 5px 15px;">
          <label>
            <input type="checkbox" ng-model="group.isSelected" ng-change="syncSelectedGroups()">
            {{group.displayName}}
          </label>
        </div>
      </li>
    </ul>
  </div>

  <!-- 调试用:展示选中结果 -->
  <div style="margin-top:15px;">
    <strong>选中的分组ID:</strong> {{selectedGroupIds.join(', ')}}
    <br>
    <strong>选中的分组详情:</strong> {{selectedGroups}}
  </div>
</div>

控制器代码

angular.module('multiSelectApp', [])
.controller('GroupSelectCtrl', function($scope) {
  // 替换成你项目中实际的分组数据
  $scope.groups = [
    { id: 1, displayName: '运营组', isSelected: false },
    { id: 2, displayName: '技术组', isSelected: false },
    { id: 3, displayName: '产品组', isSelected: false },
    { id: 4, displayName: '设计组', isSelected: false }
  ];

  // 存储选中的分组对象和ID
  $scope.selectedGroups = [];
  $scope.selectedGroupIds = [];

  // 生成下拉按钮的显示文本
  $scope.getSelectedLabel = function() {
    if ($scope.selectedGroups.length === 0) {
      return '选择分组';
    }
    return $scope.selectedGroups.map(g => g.displayName).join(', ');
  };

  // 同步选中的分组数据
  $scope.syncSelectedGroups = function() {
    $scope.selectedGroups = $scope.groups.filter(g => g.isSelected);
    $scope.selectedGroupIds = $scope.selectedGroups.map(g => g.id);
  };
});

关键逻辑说明

  1. 复选框绑定:通过ng-model绑定每个分组的isSelected属性,ng-change触发同步方法,实时更新选中状态
  2. 选中值同步:syncSelectedGroups方法通过过滤数组,提取选中的分组对象和ID,方便后续业务场景使用
  3. 按钮文本动态更新:getSelectedLabel方法根据选中状态生成下拉按钮的显示文本,无选中时显示默认提示

样式适配(可选)

如果需要和目标样式图完全匹配,可添加以下自定义CSS:

.dropdown-menu li:hover {
  background-color: #f8f9fa;
}
.dropdown-menu input[type="checkbox"] {
  margin-right: 8px;
}
.dropdown-menu {
  min-width: 180px;
}

获取选中值

在控制器中,$scope.selectedGroups包含所有选中分组的完整数据,$scope.selectedGroupIds是仅包含ID的数组,你可以在提交表单、发起请求等场景直接调用这两个变量。


内容的提问来源于stack exchange,提问作者muhammad Yousaf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:52:42