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

如何用ng-repeat定位含特定key的目标数据项并分组

解决AngularJS中ng-repeat筛选并分组展示带group属性元素的问题

没问题,我来帮你搞定这个需求!你需要用ng-repeat只渲染带有group属性的元素,还要把group为"General"的和其他分组分开展示,这里有两种实用的方案:

方案一:控制器预处理数据(推荐,无额外依赖)

这种方式在控制器里先完成数据过滤和分组,模板只负责渲染,性能更好,尤其是数据量较大时。

1. 控制器代码

假设你的原始数据存在$scope.items中,我们先过滤出带有group属性的元素,再按group值分组:

app.controller('YourController', function($scope) {
  // 你的原始JSON数据
  $scope.items = [
    { "name": "cameraasd_main_autofocus", "value": "Lasasd autofocus", "displayName": "Autofocus" },
    { "name": "screen_siasdze", "value": "5.2\asd", "displayName": "Sdascreen Size", "group": "General" },
    { "name": "camera_maindas_features", "value": "Digital Zoom,das Auto Flash, Digital image stabilization", "displayName": "Features" },
    // 可以添加更多带group属性的元素
    { "name": "battery_capacity", "value": "3000mAh", "displayName": "Battery", "group": "Hardware" }
  ];

  // 初始化分组对象
  $scope.groupedItems = {};

  // 第一步:过滤出带有group属性的元素
  const filteredItems = $scope.items.filter(item => item.hasOwnProperty('group'));

  // 第二步:按group值分组
  filteredItems.forEach(item => {
    if (!$scope.groupedItems[item.group]) {
      $scope.groupedItems[item.group] = [];
    }
    $scope.groupedItems[item.group].push(item);
  });
});

2. 模板代码

在模板里分别渲染"General"组和其他分组:

<div ng-controller="YourController">
  <!-- 单独展示General分组 -->
  <h3>*General Settings*</h3>
  <div ng-repeat="item in groupedItems.General" class="item-row">
    <strong>{{item.displayName}}</strong>: {{item.value}}
  </div>

  <!-- 展示其他所有分组 -->
  <h3>Other Groups</h3>
  <div ng-repeat="(groupName, items) in groupedItems" ng-if="groupName !== 'General'">
    <h4>{{groupName}}</h4>
    <div ng-repeat="item in items" class="item-row">
      <strong>{{item.displayName}}</strong>: {{item.value}}
    </div>
  </div>
</div>

方案二:模板中直接过滤+分组(需额外依赖)

如果你不想在控制器里处理数据,可以用AngularJS的过滤器,但原生AngularJS没有groupBy过滤器,需要引入angular-filter库(可通过npm或CDN引入)。

1. 自定义过滤带group属性的过滤器

先定义一个过滤器,筛选出带有group属性的元素:

app.filter('hasGroup', function() {
  return function(items) {
    return items ? items.filter(item => item.hasOwnProperty('group')) : [];
  };
});

2. 模板代码

直接在模板里链式使用过滤器,完成筛选和分组:

<div ng-controller="YourController">
  <!-- 展示General分组 -->
  <h3>*General Settings*</h3>
  <div ng-repeat="item in items | hasGroup | filter:{group:'General'}" class="item-row">
    <strong>{{item.displayName}}</strong>: {{item.value}}
  </div>

  <!-- 展示其他分组 -->
  <h3>Other Groups</h3>
  <div ng-repeat="(groupName, items) in items | hasGroup | filter:{group:'!General'} | groupBy:'group'">
    <h4>{{groupName}}</h4>
    <div ng-repeat="item in items" class="item-row">
      <strong>{{item.displayName}}</strong>: {{item.value}}
    </div>
  </div>
</div>

两种方案都能满足你的需求,推荐用方案一,不需要额外引入依赖,也更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:52:00