Search code examples
javascriptangularjsangularjs-ng-repeatangular-filters

Angularjs: filter items in ng-repeat containing a substring


So I have a scope variable which is set dynamically:

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

And I have an array(example) which I have to iterate using ng-repeat:

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

Here's the markup:

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

Now what I want to achieve is that in the ng-repeat loop, I print only those dates which contain the month stored in $scope.month. How can I do this using a filter?


Solution

  • You can pass arguments to a filter

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

    Then you can work the rest out in your filter

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

    demo