AngularJS嵌套ng-repeat过滤器多个参数



长期潜伏者,第一次海报。真的很喜欢你在这里的社区:)

好的,问题就解决了。目标是通过将 2 个参数传递给过滤器来过滤 ng-repeat。

我有一个嵌套的 ng-repeat,在第二次重复时,我需要根据它们的生命周期是否在当月过滤条目。

我以前用 ng-if 做过这件事,但由于我对奇数行和偶数行使用不同的 CSS,这会产生不需要的结果。

相关的 HTML 部分:

<div class="col-md-12" ng-repeat="month in monthTable">
 <div class="col-md-12">
  <h2>
   <span>{{ month.start | amDateFormat:"MMMM" | uppercase}}</span>
  </h2>
 </div>
 <div class="col-md-12">
  <div ng-class-even="'calendar_row_even'" ng-class-odd="'calendar_row_odd'"
ng-repeat="bed in syncData.beds | filter: filterListItems(month, bed) |
orderBy:'timeFrom'">
   // --> displays the unfiltered results for each month at the moment...
  </div>
 </div>
</div>

monthTable 用于确定一个月的开始和结束 + 生成名称是适当的语言环境,它填充如下:

for ( var i = 0; i < 12; i++) {
  $scope.monthTable.push({
    start: new Date(Date.UTC($scope.currentYear, i, 1)).getTime(),
    end: new Date(Date.UTC($scope.currentYear, i+1, 1)).getTime()
  })
};

到目前为止,这是不言自明的。

现在这是"应该做"过滤的函数:

$scope.filterListItems = function (month, bed) {
  console.log(month);
  console.log(bed);
  return true;
  /*return (bed.timeFrom < month.end && bed.timeUntil >= month.start);
--> this should be the code.*/
};

问题是我无法让过滤器接收 2 个参数。如果我这样写:

"filter: filterListItems(month, bed)"

月份过去了,但床没有定义

如果我这样写:

"filter: filterListItems:month:bed"

只有床被传递,但月份未定义

我不知道我做错了什么,如果有任何1可以指出我正确的方向,我将不胜感激。

你应该将你的方法声明为过滤器:

angular.module('yourApp')
    .filter('filterListItems', filterListItems);

并像下面这样调整您的方法:

function filterListItems() {
    return function(items, month) {
        // 'items' represent the objects listed by your ng-repeat
        // Now, filter the items to return only items that respect your condition.
        return items.filter(function(item) {
            return (item.timeFrom < month.end && item.timeUntil >= month.start);
        });
    }
}

并像这样使用它:

ng-repeat="bed in syncData.beds | filterListItems:month

最新更新