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

如何使用ui-select的group by属性展示按嵌套对象属性分组的列表

解决ui-select按嵌套对象属性分组展示的问题

我来帮你搞定这个ui-select的分组需求!其实ui-select本身就支持基于嵌套属性的分组,只需要正确使用group-by指令就可以了,下面给你详细的解决方案:

核心解决方案:使用group-by指向嵌套属性

假设你的allNutrientes数组里的每个对象结构是这样的(你可以根据实际结构调整):

$scope.allNutrientes = [
  { nombre: 'Vitamina C', categoria: { nombre: 'Vitaminas' } },
  { nombre: 'Hierro', categoria: { nombre: 'Minerales' } },
  { nombre: 'Vitamina D', categoria: { nombre: 'Vitaminas' } }
];

你只需要在ui-select-choices上添加group-by属性,直接指定嵌套属性的路径(比如categoria.nombre),完整代码如下:

<ui-select ng-model="selectedNutriente" theme="bootstrap">
  <ui-select-match placeholder="Elija un Nutriente...">{{$select.selected.nombre}}</ui-select-match>
  <ui-select-choices 
    repeat="a in allNutrientes | filter: $select.search | orderBy: 'categoria.nombre'"
    group-by="categoria.nombre">
    <!-- 展示选项名称,可选高亮搜索关键词 -->
    <div ng-bind-html="a.nombre | highlight: $select.search"></div>
    <!-- 可选:展示分组名称作为辅助信息 -->
    <small class="text-muted">{{a.categoria.nombre}}</small>
  </ui-select-choices>
</ui-select>

处理嵌套属性为空的情况

如果你的数据里存在嵌套对象缺失的情况(比如某个营养元素没有分类),可以自定义一个分组函数来处理默认值:

1. 在控制器里定义分组函数

$scope.getNutrienteGroup = function(item) {
  // 如果嵌套的categoria不存在,返回默认分组名
  return item.categoria && item.categoria.nombre ? item.categoria.nombre : 'Sin categoría';
};

2. 在模板里使用这个函数作为group-by的值

<ui-select-choices 
  repeat="a in allNutrientes | filter: $select.search | orderBy: 'categoria.nombre'"
  group-by="getNutrienteGroup">
  <!-- 选项内容不变 -->
</ui-select-choices>

关键注意点

  • 确保你的allNutrientes数组中的对象确实包含对应的嵌套属性,避免出现undefined导致分组异常
  • 添加orderBy过滤器可以让同组的选项排列更整齐,提升用户体验
  • 如果使用highlight过滤器,要确保已经正确引入了ui.select模块的依赖

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:47:23