在角度js中显示两个数组的交集

2024-01-10

在角度中,我在 $scope 中有两个列表。第一个是包列表,第二个是适用于它们的标签列表。例如考虑:

$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"
                }]

我想使用以下内容来显示它:

<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>

如何获得 filter: intersect() 功能? 有没有更好的方法来达到同样的目的?


你可以只使用.filter and .indexOf过滤器内的数组函数:

angular.module('myApp',[]).filter('intersect', function(){
    return function(arr1, arr2){
        return arr1.filter(function(n) {
                   return arr2.indexOf(n) != -1
               });
    };
});

然后对于 HTML 来说,它看起来像这样:

<li ng-repeat="tag in tags | intersect: pkg.tags">

http://jsfiddle.net/8u4Zg/ http://jsfiddle.net/8u4Zg/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在角度js中显示两个数组的交集 的相关文章

随机推荐