0

im a beginning student on angularjs

suppose we have a josn obj like

 [ {
        "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

<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.

how to write the fliter i'm confused

GillesC
  • 10,647
  • 3
  • 40
  • 55

1 Answers1

0

You need to create a filter and use it inside 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:

<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