如何通过ag-grid在同一模态框中动态切换数据及列定义(双点击)
解决方案:复用模态框并动态切换标题与AG-Grid列定义
我来帮你实现这个需求——两个图标触发同一个模态框,动态切换标题和AG-Grid的单个列定义,同时保留模态框的淡入效果。下面是具体的实现步骤:
1. HTML结构调整
首先修改你的图标按钮和模态框代码,把标题和AG-Grid的列定义绑定到AngularJS作用域变量上:
<!-- 第一个图标:触发Process A --> <label data-toggle="modal" data-target="#demo" data-ng-click="openModal('A')" title="Modal Process A"> <span class="fa fa-dollar"></span> </label> <!-- 第二个图标:触发Process B --> <label data-toggle="modal" data-target="#demo" data-ng-click="openModal('B')" title="Modal Process B"> <span class="fa fa-euro"></span> </label> <!-- 复用的模态框 --> <div class="modal fade" id="demo" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{modalTitle}}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <!-- AG-Grid 容器 --> <div ag-grid="gridOptions" class="ag-theme-alpine"></div> </div> </div> </div> </div>
2. AngularJS控制器逻辑
在控制器里初始化基础的列定义,然后通过openModal函数动态切换标题和目标列的配置,同时刷新AG-Grid:
angular.module('app').controller('DemoController', function($scope) { // 初始化模态框标题 $scope.modalTitle = 'Process'; // 基础AG-Grid列定义(除了要切换的列,其他列保持不变) const baseColumnDefs = [ { headerName: 'ID', field: 'id', sortable: true }, { headerName: 'Name', field: 'name', sortable: true }, // 这里是要动态切换的列,先初始化一个默认值 { headerName: 'Default Column', field: 'defaultField', editable: true } ]; // AG-Grid配置 $scope.gridOptions = { columnDefs: [...baseColumnDefs], rowData: [ { id: 1, name: 'Item 1', defaultField: 'Value 1', processAField: 'A Value 1', processBField: 'B Value 1' }, { id: 2, name: 'Item 2', defaultField: 'Value 2', processAField: 'A Value 2', processBField: 'B Value 2' } ], enableSorting: true, enableFilter: true }; // 打开模态框的通用函数,接收类型参数 $scope.openModal = function(processType) { // 切换模态框标题 $scope.modalTitle = `Process ${processType}`; // 找到要替换的列(这里假设是最后一列,你可以根据headerName或者其他标识定位) const targetColumnIndex = $scope.gridOptions.columnDefs.length - 1; // 根据类型切换列定义 if (processType === 'A') { $scope.gridOptions.columnDefs[targetColumnIndex] = { headerName: 'Process A Data', field: 'processAField', editable: true, cellStyle: { color: 'blue' } }; } else if (processType === 'B') { $scope.gridOptions.columnDefs[targetColumnIndex] = { headerName: 'Process B Data', field: 'processBField', editable: true, cellStyle: { color: 'green' } }; } // 通知AG-Grid刷新列配置 if ($scope.gridOptions.api) { $scope.gridOptions.api.refreshColumns(); } }; });
关键细节说明
- 我把两个点击函数合并成了一个
openModal,通过传入参数区分Process A和B,这样代码更简洁易维护; - 模态框的淡入效果由Bootstrap的
fade类自动处理,不需要额外逻辑; - AG-Grid通过
refreshColumns()方法来响应列定义的变化,确保表格能实时更新; - 你可以根据实际需求调整列的定位方式(比如通过
headerName查找,而不是索引),或者修改列的其他属性(比如编辑器、样式等)。
内容的提问来源于stack exchange,提问作者Koustubh Kittur
相关产品推荐
相关产品推荐

