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?
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?
Share Improve this question asked May 20, 2015 at 12:43 Tarun DugarTarun Dugar 8,9918 gold badges49 silver badges80 bronze badges 2- 1 check example with 'friends' array, exactly what you are looking for docs.angularjs/api/ng/directive/ngRepeat – Dmitri Algazin Commented May 20, 2015 at 12:47
- Really it should be a filter. docs.angularjs/api/ng/filter/filter – KnowHowSolutions Commented May 20, 2015 at 12:55
2 Answers
Reset to default 8You 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
An alternate solution would be create a new array and use it in 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.