使用过滤器比较数组并仅返回唯一结果

时间:2014-12-23 16:20:43

标签: angularjs angular-filters

我正从远程源检索2个JSON数组。我正在尝试将结果从数组X过滤到数组Y,并且只返回两者中的唯一值。 stackoverflow上的所有问题都是用于过滤1个数组而不是一组多个。

1 个答案:

答案 0 :(得分:1)

您可以使用与a8m/angular-filter

中的unique过滤器类似的内容



(function() {
  angular.module('myApp', ['angular.filter'])
    .controller('HomeController', ['$scope',
      function($scope) {
        $scope.first = [{id: 1, name:'first'},{id: 2, name:'second'}, 
{id: 3, name:'third'}, {id: 4, name: 'fourth'} ];

        $scope.second = [{id: 1, name:'first'},{id: 2, name:'second'}, 
{id: 5, name: 'fifth'} ];
      }
    ]);
}());

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.1/angular-filter.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="HomeController">
    <ul>
      <li ng-repeat="item in first.concat(second) | unique:'id'">
        {{item.id}} : {{ item.name }}
      </li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;