简体   繁体   English

如何通过ng-repeat angularjs中的obj属性过滤数据

[英]how to filter the data by obj's attribute in ng-repeat angularjs

im a beginning student on angularjs 我是angularjs的新手

suppose we have a josn obj like 假设我们有一个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,
    }
]

ngRepeat ngRepeat

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

we have two data in MAY (05-31 ,05-11)in the json obj,and i want to keep one data in a month, just keep the second one. 我们在json obj中的MAY(05-31,05-11)中有两个数据,我想在一个月内保留一个数据,只保留第二个。

how to write the fliter i'm confused 如何写我感到困惑的书

You need to create a filter and use it inside ng-repeat. 您需要创建一个过滤器,并在ng-repeat中使用它。 The syntax to create filters is like this: 创建过滤器的语法如下:

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);
     }
  })

To apply the logic filtering you ask for, you can create a filter like this: 要应用您要求的逻辑过滤,您可以创建如下过滤器:

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;
  }
}

With this filter, the html template would be something like this: 使用此过滤器,html模板将如下所示:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM