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

如何用AngularJS按性别分组展示数据库数据?

解决AngularJS按性别分组展示数据的问题

嘿,我来帮你搞定这个分组展示的需求!你已经拿到了结构化的JSON数据,接下来只需要两步:先在控制器里把数据按性别分组,再在视图里渲染分组后的内容。

第一步:在控制器中对数据进行分组处理

你可以在AngularJS的控制器里添加一个分组逻辑,把$scope.data按Sex字段归类。这样视图层就能直接用分组好的数据了:

angular.module('yourAppName', [])
  .controller('yourControllerName', function($scope) {
    // 你的原始数据
    $scope.data = [
      {"Name":"Jack","Age":20,"Sex":"Male"},
      {"Name":"Jill","Age":22,"Sex":"Male"},
      {"Name":"Annie","Age":19,"Sex":"Female"},
      {"Name":"Stephanie","Age":17,"Sex":"Female"}
    ];

    // 按性别分组的逻辑
    $scope.groupedData = {};
    angular.forEach($scope.data, function(person) {
      // 如果当前性别还没有分组,先创建空数组
      if (!$scope.groupedData[person.Sex]) {
        $scope.groupedData[person.Sex] = [];
      }
      // 将当前用户添加到对应性别的分组中
      $scope.groupedData[person.Sex].push(person);
    });
  });

第二步:在HTML视图中渲染分组数据

接下来用AngularJS的ng-repeat指令,先遍历分组的键(也就是Male/Female),再遍历每个分组下的用户数据:

<div ng-app="yourAppName" ng-controller="yourControllerName">
  <div ng-repeat="(gender, people) in groupedData">
    <!-- 显示性别分组标题 -->
    <strong>{{ gender }}</strong>
    <!-- 遍历当前分组下的所有用户 -->
    <div ng-repeat="person in people">
      {{ person.Name }} | {{ person.Age }}
    </div>
  </div>
</div>

这样渲染出来的UI就会完全符合你想要的格式:

Male
Jack | 20
Jill | 22
Female
Annie | 19
Stephanie | 17

如果需要固定分组顺序(比如强制先显示Male再显示Female),可以在分组后手动调整对象的键顺序,或者给ng-repeat添加排序过滤器,比如ng-repeat="(gender, people) in groupedData | orderBy: '-gender'"(AngularJS 1.5+版本能较好支持对象键的排序)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:22:37