program story

AngularJS 커스텀 필터 함수

inputbox 2020. 9. 16. 07:41
반응형

AngularJS 커스텀 필터 함수


내 컨트롤러 내에서 객체 배열을 필터링하고 싶습니다. 이러한 각 객체는 목록뿐만 아니라 문자열을 포함 할 수있는 맵입니다.

$filter('filter')(array, function)형식을 사용해 보았지만 함수 내 배열의 개별 요소에 액세스하는 방법을 모르겠습니다. 여기 내가 원하는 것을 보여주는 스 니펫이 있습니다.

$filter('filter')(array, function() {
  return criteriaMatch(item, criteria);
});

그런 다음에서 criteriaMatch()개별 속성이 일치하는지 확인합니다.

var criteriaMatch = function(item, criteria) {
  // go thro each individual property in the item and criteria
  // and check if they are equal
}

컨트롤러에서이 모든 작업을 수행하고 목록 목록을 컴파일하고 범위에 설정해야합니다. 따라서이 $filter('filter')방법으로 만 액세스하면 됩니다. 지금까지 인터넷에서 찾은 모든 예제에는 함수 내에서 정적 기준 검색이 있으며 기준 객체를 전달하지 않고 배열의 각 항목에 대해 테스트하지 않습니다.


다음과 같이 사용할 수 있습니다. http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview

찾은 것처럼 filter배열에서 항목별로 항목을 받아들이는 조건 자 함수를 허용합니다. 따라서 주어진를 기반으로 조건 자 함수를 생성하면 criteria됩니다.

이 예제에서는 criteriaMatch주어진 .NET과 일치하는 조건 자 함수를 반환하는 함수입니다 criteria.

주형:

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

범위:

$scope.criteriaMatch = function( criteria ) {
  return function( item ) {
    return item.name === criteria.name;
  };
};

다음 filter은 HTML 요소가 아닌 AngularJS JavaScript 내에서 사용하는 방법의 예입니다 .

이 예에는 각각 이름과 3 자 ISO 코드가 포함 된 국가 레코드 배열이 있습니다.

이 목록을 통해 특정 3 자 코드와 일치하는 레코드를 검색하는 함수를 작성하려고합니다.

다음은 사용 하지 않고 수행하는 방법입니다 filter.

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.
    for (var i = 0; i < $scope.CountryList.length; i++) {
        if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
            return $scope.CountryList[i];
        };
    };
    return null;
};

네, 그게 잘못이 아닙니다.

그러나 다음을 사용하여 동일한 기능이 어떻게 보이는지 다음과 filter같습니다.

$scope.FindCountryByCode = function (CountryCode) {
    //  Search through an array of Country records for one containing a particular 3-character country-code.
    //  Returns either a record, or NULL, if the country couldn't be found.

    var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })

    //  If 'filter' didn't find any matching records, its result will be an array of 0 records.
    if (matches.length == 0)
        return null;

    //  Otherwise, it should've found just one matching record
    return matches[0];
};

훨씬 깔끔합니다.

filter결과 (일치하는 레코드 목록)로 배열 반환 하므로이 예제에서는 레코드 1 개 또는 NULL을 반환하려고합니다.

도움이 되었기를 바랍니다.


또한 컨트롤러에서 필터를 동일한 방식으로 사용하려면 여기에서 수행하십시오.

<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
  {{ item }}
</div>

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

var filteredItems =  $scope.$eval('items | filter:filter:criteriaMatch(criteria)');

참고 URL : https://stackoverflow.com/questions/16474091/angularjs-custom-filter-function

반응형