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

如何通过rowTemplate为表格每行首列添加类?

给UI-Grid选择列(首列)添加自定义类的解决方案

嘿,刚好我之前做过类似的UI-Grid样式定制,给你两个可行的方案,其中第二个更推荐,维护起来更省心:

方案1:优化你现有的rowTemplate写法

你已经在用rowTemplate实现行级样式了,那只要在遍历列的时候,判断当前列是不是内置的选择列(UI-Grid内置选择列的colDef.name固定是ui-grid-selection),就能给首列的选择框单元格追加自定义类。修改你的rowTemplate里的class属性:

<div ng-if="grid.appScope.rowFormatter( row ) == 'lowImportance' " 
     ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" 
     class="ui-grid-cell {{col.colDef.name === 'ui-grid-selection' ? 'your-custom-selection-class' : ''}} green-importance">
  <!-- 原有单元格内容 -->
</div>

关键说明

  • 这个写法完全兼容你现有的rowFormatter逻辑,只会给选择列额外叠加自定义类
  • 如果你的选择列是自定义的(不是UI-Grid内置的),把判断条件里的ui-grid-selection换成你自定义列的name值即可

方案2:更简洁的列配置(推荐)

其实不用折腾rowTemplate,直接在列定义里通过cellClass配置就能精准给选择列加类,代码更清晰,后续维护也方便:

$scope.gridOptions = {
  enableRowSelection: true,
  enableRowHeaderSelection: true,
  columnDefs: [
    // 针对内置选择列配置自定义类
    { 
      name: 'ui-grid-selection',
      // 固定类写法,直接指定样式类名
      cellClass: 'your-custom-selection-class',
      // 也可以用动态函数,结合行数据实现更灵活的样式
      // cellClass: function(grid, row, col, rowRenderIndex, colRenderIndex) {
      //   // 这里可以复用你原来的rowFormatter逻辑
      //   return grid.appScope.rowFormatter(row) === 'lowImportance' ? 'green-importance your-custom-selection-class' : 'your-custom-selection-class';
      // }
    },
    // 其他业务列配置
    { name: 'userName', displayName: '用户名' },
    { name: 'email', displayName: '邮箱' }
  ]
};

关键说明

  • 如果是UI-Grid自动生成的选择列,只要name设为ui-grid-selection就能精准匹配
  • 动态cellClass函数可以直接复用你现有的rowFormatter逻辑,实现行级样式和列级样式的联动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:52:14