在角度js中显示两个数组的交集 [英] Displaying intersection of two arrays in angular js
本文介绍了在角度js中显示两个数组的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在angular中,我在$ scope中有两个列表.一个是软件包列表,第二个是适用于它们的标签列表.考虑例如:
In angular I have two lists in $scope. One is a list of packages, and the second is a list of tags that apply to them. Consider for example:
$scope.packages = [ {
name = "pkg1",
tags = [ 1, 3]
}, {
name = "pkg2",
tags = [ 2, 3]
}]
$scope.tags = [ {
id = 1,
name = "tag1"
}, {
id = 2,
name = "tag2"
}, {
id = 3,
name = "tag3"
}]
我想使用以下内容来显示此内容:
I want to display this using something along the lines of:
<ul>
<li ng-repeat = "pkg in packages">
{{pkg.name}}
<ul>
<li ng-repeat = "tag in tags | filter : intersect(pkg.tags)">
{{tag.name}}
</li>
</ul>
</li>
</ul>
如何获取过滤器:intersect()功能? 有没有更好的方法可以达到相同的目的?
How can I get the filter: intersect() functionality? Is there a better way of achieving the same end?
推荐答案
您可以在过滤器内部使用.filter
和.indexOf
数组函数:
You could just use the .filter
and .indexOf
array functions inside of a filter:
angular.module('myApp',[]).filter('intersect', function(){
return function(arr1, arr2){
return arr1.filter(function(n) {
return arr2.indexOf(n) != -1
});
};
});
然后对于HTML,它看起来像这样:
And then for the HTML it looks like this:
<li ng-repeat="tag in tags | intersect: pkg.tags">
这篇关于在角度js中显示两个数组的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文