最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angularjs: filter items in ng-repeat containing a substring - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 8

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

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.

发布评论

评论列表(0)

  1. 暂无评论