【问题标题】:how to filter the data by obj's attribute in ng-repeat angularjs如何在ng-repeat angularjs中通过obj的属性过滤数据
【发布时间】:2015-07-07 09:53:40
【问题描述】:

我是 angularjs 的初学者

假设我们有一个类似 josn 的 obj

 [ {
        "Title": "a",
        "Date": "2015-05-31",
        "a": "11",
        "b": 22,
    },
     {
        "Title": "b",
        "Date": "2015-05-11",
       "a": "33",
        "b": 44,
    },
    {
        "Title": "c",
        "Date": "2015-04-11",
       "a": "55",
        "b": 66,
    },
    {
        "Title": "d",
        "Date": "2015-03-03",
       "a": "11",
        "b": 22,
    }
]

ng重复

<li ng-repeat="obj in objs">{{obj.Date  | date:"MM/yyyy"}}</li>

我们在 json obj 中有两个 5 月 (05-31 ,05-11) 的数据,并且 我想在一个月内保留一个数据,只保留第二个。

我很困惑怎么写过滤器

【问题讨论】:

标签: javascript angularjs filter ng-repeat


【解决方案1】:

您需要创建一个过滤器并在 ng-repeat 中使用它。 创建过滤器的语法如下:

angular
  .module('myModule')
  .filter('myFilter', function myFilter(service1, service2) { //to ask for deps
     return function(input) { //here you do the real filtering
        return doSomethingWithInput(input);
     }
  })

要应用您要求的逻辑过滤,您可以像这样创建一个过滤器:

angular
  .module('myModule')
  .filter('oncePerMonth', oncePerMonth);

function oncePerMonth() {
  return function (data) {
    var filtered = [], months = [];
    data.forEach(function(item){
      var month = item.Date.substr(0,7);
      if (~~months.indexOf(month)){
        months.push(month);
        filtered.push(item);
      }
    });
    return filtered;
  }
}

使用此过滤器,html 模板将如下所示:

<li ng-repeat="obj in vm.objs | oncePerMonth">
   {{obj.Date | date:"MM/yyyy"}} {{obj.Title}}
</li>

您可以在此处找到有效的 Plnkr:http://plnkr.co/edit/sg0wWPuUE0cJwoZj2KuS?p=preview

【讨论】:

  • 哇,非常感谢你,我从你的回答中看到了很多谢谢你!
猜你喜欢
  • 2014-01-30
  • 2014-12-27
  • 1970-01-01
  • 2015-04-28
  • 2016-07-26
  • 1970-01-01
  • 1970-01-01
  • 2019-10-07
  • 1970-01-01
相关资源
最近更新 更多