簡體   English   中英

如何通過ng-repeat angularjs中的obj屬性過濾數據

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

我是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,
    }
]

ngRepeat

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

我們在json obj中的MAY(05-31,05-11)中有兩個數據,我想在一個月內保留一個數據,只保留第二個。

如何寫我感到困惑的書

您需要創建一個過濾器,並在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM