2017-01-10 4 views
2
여기

ng-repeat를 사용하여 내 HTML의 작은 예입니다 : JS에서특정 객체 속성의 배열을 기반으로 객체 배열을 필터링하는 방법은 무엇입니까?

<div ng-repeat="item in vm.templateList | filter: vm.myFilter"> 
    <h3>{{item.Code}}</h3> 
</div> 

이 파일 vm.templateList (예를 들어) 다음과 같습니다

vm.templateList = [{Code: 'a', ID: 1}, 
        {code: 'a', ID: 2}, 
        {code: 'b', ID: 3}, 
        {code: 'c', ID: 4}]; 

내가 모두를위한이 목록을 필터링 할 상상 ID가 1이고 ID가 2 인 항목도 있습니다.

내가 원래 작성한 내용은 다음과 같습니다.

vm.filter = {ID: 1}; 

하지만 이것은 1 ID로만 목록을 필터링 할 수있었습니다. 누구든지 길을 제안 할 수 있습니까?

+0

당신은 [사용자 정의 필터]를 만들 수 있습니다 (https://docs.angularjs.org/guide/filter#creating-custom-filters) – yarons

답변

3

당신은 당신의 응용 프로그램에 다음 AngularJS와 필터를 추가 할 수 있습니다

// add a custom filter to your module 
angular.module('MyModule').filter('myFilter', function() { 
    // the filter takes an additional input filterIDs 
    return function(inputArray, filterIDs) { 
     // filter your original array to return only the objects that 
     // have their ID in the filterIDs array 
     return inputArray.filter(function (entry) { 
      return this.indexOf(entry.ID) !== -1; 
     }, filterIDs); // filterIDs here is what "this" is referencing in the line above 
    }; 
}); 

당신은 다음과 같은 컨트롤러의 필터 배열을 선언 :

vm.IDs = [1, 2]; 

그런 다음 뷰는 다음과 같아야합니다

<div ng-repeat="item in vm.templateList | myFilter: vm.IDs"> 
    <h3>{{item.Code}}</h3> 
</div> 
+0

고마워요 :) –

+0

당신은 대부분 환영합니다. –

2

다음과 같이 사용할 수 있습니다.

HTML :

<section> 
    <div ng-repeat="item in vm.templateList | filter:checkFilterOptions"> 
     <h3>{{item.Code}}</h3> 
    </div> 
</section> 

JS :

$scope.vm = {}; 
    $scope.vm.templateList = [ 
        {Code: 'a', ID: 1}, 
        {Code: 'a', ID: 2}, 
        {Code: 'b', ID: 3}, 
        {Code: 'c', ID: 4} 
        ]; 

    $scope.filterOptions = [1,2,3]; 

    $scope.checkFilterOptions = function(value, index) { 
     return value.ID && $scope.filterOptions.indexOf(value.ID) !== -1; 
    } 
관련 문제