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

Angular UI-Grid:cellTemplate中获取并传递行索引失败求助

在Angular UI-Grid的cellTemplate中获取行索引的解决方案

嗨,我来帮你搞定这个问题~你之前尝试用$index、$parent.$index没成功,是因为Angular UI-Grid的cellTemplate作用域和普通ng-repeat的作用域不一样,它有自己内置的行对象可以直接用。

下面给你两种实用的方法:

方法一:直接使用UI-Grid内置的row.index属性

UI-Grid会给每个cell的作用域注入row对象,其中row.index就是当前行在当前页的索引(从0开始计数)。你只需要修改你的ng-click代码,把row.entity.$index换成row.index就行:

ng-click="grid.appScope.selectItem($event, row.index);"

如果你的需求是在单元格里显示行号(比如从1开始),可以直接在cellTemplate里这样写:

cellTemplate: '<div class="ui-grid-cell-contents" ng-click="grid.appScope.selectItem($event, row.index)">{{row.index + 1}}</div>'

方法二:获取全局行索引(跨分页场景)

如果你的表格开启了分页,想要获取整个数据集里的全局行索引,那可以结合分页参数计算:

ng-click="grid.appScope.selectItem($event, (grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + row.index);"

这个公式的逻辑是:(当前页码-1)*每页条数 + 当前页行索引,就能得到从0开始的全局行索引。

小提醒

  • row.index是UI-Grid原生提供的属性,不需要额外定义,直接在cellTemplate里用就行
  • 别混淆row.index和row.entity的属性,row.entity是当前行绑定的数据对象,本身没有$index属性哦

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:55:06