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

javascript - AngularJS: how to find objects from an array of objects, given an array of property values in an array, using $filt

programmeradmin1浏览0评论

Have a set of objects in an array (items array) that have property

item_id:
[{item_id:1,...},{item_id:2,...}...]

Have another array with a set of

item_ids:
[2, 8, 10]

How do I use the $filter of angularjs to get array of objects from items array where item_id matches those in item_ids array.

Have a set of objects in an array (items array) that have property

item_id:
[{item_id:1,...},{item_id:2,...}...]

Have another array with a set of

item_ids:
[2, 8, 10]

How do I use the $filter of angularjs to get array of objects from items array where item_id matches those in item_ids array.

Share Improve this question edited May 31, 2015 at 13:39 Dhanuka 2,8325 gold badges30 silver badges38 bronze badges asked May 31, 2015 at 13:27 mssuleymssuley 581 gold badge1 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

You can use custom filter to do this kind of filtration. and you can use use $filter service if you want to do that in code instead of template.

Filter Guide

See the below code.

var app = angular.module('app', []);

app.controller('ctrl', function($scope, $filter) {

  $scope.items = [{
    item_id: 1
  }, {
    item_id: 2
  }, {
    item_id: 3
  }, {
    item_id: 4
  }];

  $scope.findList = [2, 4];
  $scope.findList2 = [3];

  // Using $filter service.
  $scope.usingservice = $filter('findobj')($scope.items, [1, 3])
});

app.filter('findobj', function() {

  return function(list, obj) {

    return list.filter(function(l) {
      if (obj.indexOf(l.item_id) >= 0) {
        return true;
      }
    });

  };
})
<script src="https://ajax.googleapis./ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="ctrl">
    <div ng-repeat="item in items | findobj: findList">
      {{item}}
    </div>
    <hr/>
    <div ng-repeat="item in items | findobj: findList2">
      {{item}}
    </div>
    <hr/>{{usingservice}}
  </div>
</div>

发布评论

评论列表(0)

  1. 暂无评论