角度过滤对象的JSON对象

时间:2014-07-24 02:24:25

标签: json angularjs

我遇到了一个问题,试图根据routeparam过滤我的数据。我相信这可能是因为我的JSON构建方式。从我可以告诉角度是不能过滤对象或对象。是否有自定义过滤器?这是我使用http://secret-hollows-7338.herokuapp.com/events

的页面

我的JSON在这里

'year': {    
'August': [
    {
      'day':'9', 
      'title':'Dave Ramsey\'s Financial Peace University', 
      'summary': 'Financial Peace University (FPU) is a biblically-based, life-changing program that teaches people how to make wise decisions with money. You will be empowered with the practical skills and confidence needed...', 
      'decription': 'cal desc'
    },
    {
      'day':'17', 
      'title':'Divorce & Beyond Seminar', 
      'summary': 'If you are separated from your spouse, going through a divorce or are divorced, we encourage you to seek support. We understand the feelings of guilt, rejection, fear, confusion, isolation,...', 
      'decription': 'cal desc two'
    },
          ],
  'September': [
    {
      'day':'9 sep', 
      'title':'sep title', 
      'summary': 'sep summ', 
      'decription': 'sep desc'
    }
          ]
}

我对路线参数的过滤逻辑(我将密钥作为路径参数传递)

$scope.month={};
$scope.month=$routeParams.id; 

我的观点逻辑

 <div class="events" ng-repeat="cal in calendar[0].year">
  <div ng-repeat="(val, key) in cal">
      <a href="/events/{{key.day}}">
        <article class="eventslist">
           <div class="numberedDate">
             <h3>{{key.day}}</h3>
            </div>
            <div class="calInfo">
               <h5>{{key.title}}</h5>
               <p>{{key.summary}}&nbsp;<a>more</p>
             </div>
          </article>
      </a>
  </div>

我想将此作为我的过滤器使用,但由于某种原因它无法正常工作。

<div class="calendar" ng-repeat="cal in calendar[0].year | filter:month">

1 个答案:

答案 0 :(得分:1)

filter过滤器不支持对对象进行过滤。

您的calendar[0].year是一个对象,而不是数组,似乎您希望按其键进行过滤。

如果是这种情况,您可以编写如下自定义过滤器:

appModule.filter('filterKey', function() {
  function comparator(a, b) {
    return (''+a).toLowerCase().indexOf((''+b).toLowerCase()) > -1;
  }

  return function(obj, searchKey) {
    var filtered = {};
    angular.forEach(obj, function(value, key) {
      if (comparator(key, searchKey)) {
        filtered[key] = value;
      }
    });
    return filtered;
  };
})

ng-repeat

<div class="calendar" ng-repeat="(key, val) in calendar[0].year | filterKey:month">

希望这有帮助。