programing

AngularJS 사용자 지정 필터 기능

lastmemo 2023. 3. 22. 20:38
반응형

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지정된 에 일치하는 술어 함수를 반환하는 함수입니다.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당신의 Angular 내에서(HTML 요소가 아닌) JS 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

반응형