Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

angularjs - Is it possible to filter angular.js by containment in another array?

So if I have an array:

$scope.letters = 
[{"id":"a"},
{"id":"b"},
{"id":"c"}];

And another array

$scope.filterBy = ["b","c","d"];

And I want to have some ng-repeat to filter $scope.letters by only items that appear in $filterBy.

I want to be able to do something to the effect of:

<span ng-repeat="{{letter in letters|filter: letter.id in filterBy }} > {{letter.id}} </span>

And have it print b,c

I know this is a really stupid example, but is there a way to filter an angular.js expression based on the contents of another array object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update

Here's an angular module (based on @InviS answer) to easily implement this filter inside your angular application: filters-inArrayFilter


Here's the angular filters approach based on @InviS answer:

The filter should be like this:

.filter('inArray', function($filter){
    return function(list, arrayFilter, element){
        if(arrayFilter){
            return $filter("filter")(list, function(listItem){
                return arrayFilter.indexOf(listItem[element]) != -1;
            });
        }
    };
});

where list is the list you're filtering (this param is set by default by angular), arrayFilter is the array you're using as filter, and element is the name of the property to filter in your list.

To use this filter you use your ng-repeat as:

<div ng-repeat='letter in letters | inArray:filterBy:"id"'>{{letter.id}}</div>

where inArray is the filter, filterBy (the first argument of this filter) is your array to match against, and "id" (second argument) is the element of the list you want to match against the array.

You can try this live example using the angular filters approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...