Angularjs: 过滤 ng-repeat 中包含子字符串的项目

Angularjs: filter items in ng-repeat containing a substring

所以我有一个动态设置的范围变量:

$scope.month = 'June'; //this will be a runtime assignment

我有一个数组(示例),我必须使用 ng-repeat 对其进行迭代:

$scope.dates = ['12 June, 2015', '12 April, 2015', '13 May, 2015' ];

这是标记:

<div ng-repeat = "date in dates">
    {{date}}
</div>

现在我想要实现的是在 ng-repeat 循环中,我只打印那些包含存储在 $scope.month 中的月份的日期。我如何使用过滤器执行此操作?

另一种解决方案是创建一个新数组并在 ng-repeat 中使用它。

HTML:

<div ng-repeat = "date in dates1">
    {{date}}
</div>

JS:

$scope.month = 'June';
    $scope.dates = ['12 June, 2015', '12 April, 2015', '13 May, 2015' ];
    $scope.dates1 = $scope.dates.map(function(item){
        if(item.indexOf($scope.month) != -1){
          return item;
        }
    })

Fiddle here.

您可以将参数传递给过滤器

<div ng-repeat="date in dates | filterByMonth:month"></div>

然后你可以在你的过滤器中解决剩下的问题

myApp.filter("filterByMonth", function() { 
    return function (dates, month) {
        return dates.filter(function (item) {
            return item.indexOf(month) > -1;    
        });
    };
});

demo