如何在AngularJS中为表格实现多选下拉筛选功能?
AngularJS表格多选下拉筛选解决方案
现有代码问题修正
先修正你代码中的基础错误:
- JSON数据每个对象间缺少逗号,会引发语法错误
- 表格
ng-repeat语法不完整,user in products后缺少闭合引号 - 原生
<select>是单选控件,无法直接实现多选功能 - 已尝试代码中误用
$scope.users,实际数据存于$scope.products,且逻辑不匹配多选筛选需求
最优实现方案
推荐使用AngularUI的ui-select组件实现友好的多选下拉筛选,以下是完整实现步骤:
1. 依赖准备
需要引入AngularJS、angular-ui-select和angular-sanitize的脚本与样式文件(自行从官方渠道获取资源)。
2. 模块配置
在你的AngularJS模块中注入所需依赖:
angular.module('myApp', ['ui.select', 'ngSanitize'])
3. 完整代码实现
HTML部分
<div ng-app="myApp" ng-controller="myCtrl"> <!-- 多选下拉筛选框 --> <ui-select multiple ng-model="selectedInstitutes" theme="bootstrap" placeholder="Select Institutes"> <ui-select-match placeholder="Select Institutes">{{$item}}</ui-select-match> <ui-select-choices repeat="institute in (products | unique:'Institute') track by institute"> {{institute}} </ui-select-choices> </ui-select> <!-- 筛选后的表格 --> <table> <thead> <th>Institute</th> </thead> <tbody> <tr ng-repeat="user in products | filterByInstitute:selectedInstitutes"> <td>{{user.Institute}}</td> </tr> </tbody> </table> </div>
JavaScript部分
angular.module('myApp', ['ui.select', 'ngSanitize']) .controller('myCtrl', function($scope, $filter) { // 修正后的数据源 $scope.products = [ {"Institute": "Academy for Coaching Excellence"}, {"Institute": "Sample for training Excellence"}, {"Institute": "Demo for education Excellence"}, {"Institute": "Academy for best Excellence"} ]; // 存储选中的机构数组 $scope.selectedInstitutes = []; // 自定义筛选过滤器 $scope.$filter('filterByInstitute', function() { return function(items, selected) { // 未选中任何机构时返回全部数据 if (!selected || selected.length === 0) { return items; } // 筛选出机构在选中列表中的项 return $filter('filter')(items, function(item) { return selected.indexOf(item.Institute) !== -1; }); }; }); });
备选方案:原生多选select
如果不想引入第三方组件,可使用原生多选<select>,但交互体验较差:
<select multiple ng-model="selectedInstitutes" size="4"> <option ng-repeat="institute in (products | unique:'Institute')" value="{{institute}}">{{institute}}</option> </select>
表格筛选逻辑与上述方案一致,无需修改。
内容的提问来源于stack exchange,提问作者Maya
相关产品推荐
相关产品推荐

