如何在AngularJS表格中遍历多个下拉框获取选中值
解决AngularJS表格多行下拉框选中值收集问题
你的核心问题在于下拉框的模型没有绑定到每行的迭代对象上——当前所有行的下拉框都共用了全局作用域的AndOrmodel、Fieldsmodel等变量,这就导致不管你选哪一行的下拉框,都会覆盖同一个值,自然没法区分每行的选中状态。
下面是具体的修改方案:
第一步:把模型绑定到每行的m对象上
修改HTML中每个下拉框的ng-model,将其关联到当前迭代的m属性,这样每行的选中值会独立存储在对应的FilterOptions元素中:
<table class="filtertable" ng-show="FilterOptions"> <thead> <th>And/Or</th> <th>Field</th> <th>Operator</th> <th>Value</th> </thead> <tbody ng-repeat="m in FilterOptions"> <tr> <!-- 绑定到m的selectedAndOr属性 --> <td><select ng-model="m.selectedAndOr" ng-show="m.AndOr" ng-options="option for option in m.AndOr"></select></td> <!-- 绑定到m的selectedField属性 --> <td> <select ng-model="m.selectedField" ng-options="o as o for o in m.Fields"></select> </td> <!-- 绑定到m的selectedOperator属性(注意这里是对象,不是字符串) --> <td> <select ng-model="m.selectedOperator" ng-options="Operator.OperatorName for Operator in m.Operators track by Operator.OperatorId"></select> </td> <td> <!-- 调整判断条件:用选中的Operator对象的名称来判断 --> <select ng-model="m.selectedOperField" ng-if="m.selectedOperator && m.selectedOperator.OperatorName.indexOf('Field') > -1" ng-options="o as o for o in m.Fields"></select> <input type="text" ng-if="!m.selectedOperator || m.selectedOperator.OperatorName.indexOf('Field') == -1" ng-model="m.searchValue" /> </td> <td> <p> <a href="#" ng-click="Add($index)" title="Add"> <span class="glyphicon glyphicon-plus" style="color:green;"></span> </a> </p> </td> <td> <a href="#" ng-click="Remove($index)" title="Remove this filter line"> <span class="glyphicon glyphicon-minus" style="color:red"></span> </a> </td> </tr> </tbody> <tfoot> <tr> <td colspan="4"> <p> <a href="#" ng-click="Add()" title="Add"> <span class="glyphicon glyphicon-plus" style="color:green"></span>Add new clasue </a> </p> </td> <td> <input type="button" value="Save" ng-click="SaveMasterSearch()" /> </td> </tr> </tfoot> </table>
第二步:在控制器中收集选中值
现在每行的选中值都存在FilterOptions的每个元素里了,你只需要在SaveMasterSearch函数中遍历这个数组,提取需要的属性即可组成目标对象数组:
$scope.SaveMasterSearch = function() { // 遍历FilterOptions,收集每行的选中数据 const filterArray = $scope.FilterOptions.map(item => { return { andOr: item.selectedAndOr, field: item.selectedField, operatorId: item.selectedOperator ? item.selectedOperator.OperatorId : null, operatorName: item.selectedOperator ? item.selectedOperator.OperatorName : null, value: item.selectedOperField || item.searchValue // 取下拉框或输入框的值 }; }); // 这里可以使用filterArray做后续操作,比如提交到后端 console.log('收集到的筛选条件:', filterArray); };
关键说明
- 为什么要绑定到
m对象?因为ng-repeat会为每行创建一个子作用域,绑定到m的属性可以确保每行的数据独立,不会互相覆盖。 - 对于Operator下拉框,因为你用了
track by Operator.OperatorId,所以m.selectedOperator是整个Operator对象,判断的时候要使用对象的OperatorName属性,而不是直接用字符串判断。 - 最后收集数据时,你可以根据实际需求调整要提取的属性,比如只存Operator的ID而不是整个对象。
内容的提问来源于stack exchange,提问作者Bharath Gajjala
相关产品推荐
相关产品推荐

