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

如何用月份下拉框在AngularJS中筛选JSON事件数据?

实现AngularJS月份下拉框筛选事件数据

别担心!作为AngularJS新手,实现月份筛选其实没那么复杂,咱们用自定义过滤器就能轻松搞定,这也是Angular里处理这类需求的标准方案。下面是一步步的实现步骤和完整代码示例:

1. 准备月份下拉选项

首先在你的控制器里定义月份列表,既可以用数字也可以用带名称的选项,方便用户选择:

angular.module('myApp', [])
.controller('EventController', function($scope) {
  // 你的事件数据
  $scope.events = [
    { "id": "4330", "title": "Sweet Diezel Jenkins", "subtitle": null, "date": "2018-05-25 21:00:00" },
    { "id": "6401", "title": "Patricia Avis", "subtitle": null, "date": "2018-06-29 21:00:00" }
  ];

  // 月份选项:value是数字月份,name是显示名称
  $scope.months = [
    {value: 0, name: '全部月份'},
    {value: 1, name: '1月'},
    {value: 2, name: '2月'},
    {value: 3, name: '3月'},
    {value: 4, name: '4月'},
    {value: 5, name: '5月'},
    {value: 6, name: '6月'},
    {value: 7, name: '7月'},
    {value: 8, name: '8月'},
    {value: 9, name: '9月'},
    {value: 10, name: '10月'},
    {value: 11, name: '11月'},
    {value: 12, name: '12月'}
  ];

  // 默认选中全部月份
  $scope.selectedMonth = 0;
});

2. 创建自定义月份过滤器

接下来创建一个自定义过滤器,用来提取事件日期中的月份,并和选中的月份对比:

angular.module('myApp')
.filter('monthFilter', function() {
  return function(events, selectedMonth) {
    // 如果选中全部月份,直接返回所有事件
    if (selectedMonth === 0) {
      return events;
    }
    // 筛选出月份匹配的事件
    return events.filter(function(event) {
      // 从date字符串中提取月份(格式是YYYY-MM-DD,所以索引4-5是月份部分)
      const eventMonth = parseInt(event.date.substring(5, 7), 10);
      return eventMonth === selectedMonth;
    });
  };
});

3. 在视图中使用筛选器和下拉框

最后在HTML里添加下拉框,并在ng-repeat中应用我们的自定义过滤器:

<div ng-app="myApp" ng-controller="EventController">
  <!-- 月份下拉筛选框 -->
  <select ng-model="selectedMonth" ng-options="month.value as month.name for month in months">
  </select>

  <!-- 显示筛选后的事件列表 -->
  <div ng-repeat="event in events | monthFilter:selectedMonth">
    <h3>{{event.title}}</h3>
    <p>日期:{{event.date}}</p>
  </div>
</div>

关键说明

  • 我们通过event.date.substring(5,7)提取日期字符串中的月份部分(比如"2018-05-25"会得到"05"),再转成数字和选中的月份对比。
  • 过滤器里做了判断:如果选中的是0(全部月份),就直接返回所有数据,避免不必要的筛选。
  • 这个方案可以和你已有的“按事件类型筛选”功能结合,只需要在ng-repeat里叠加多个过滤器即可,比如events | typeFilter:selectedType | monthFilter:selectedMonth。

这样就能轻松实现月份下拉框的筛选功能啦,是不是很简单? 😊

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:04:13