Program Tip

AngularJS : 사용자 지정 필터 및 ng-repeat

programtip 2020. 11. 6. 19:05
반응형

AngularJS : 사용자 지정 필터 및 ng-repeat


저는 AngularJS 초보자이고 몇 가지 필터를 사용하여 JSON을 가져와 ng-repeat를 통해 해당 데이터의 다양한 비트를 렌더링하는 작은 개념 증명 자동차 대여 목록 앱을 구축하고 있습니다.

   <article data-ng-repeat="result in results | filter:search" class="result">
        <header><h3>{{result.carType.name}}, {{result.carDetails.doors}} door, &pound;{{result.price.value}} - {{ result.company.name }}</h3></header>
            <ul class="result-features">
                <li>{{result.carDetails.hireDuration}} day hire</li>
                <li data-ng-show="result.carDetails.airCon">Air conditioning</li>
                <li data-ng-show="result.carDetails.unlimitedMileage">Unlimited Mileage</li>
                <li data-ng-show="result.carDetails.theftProtection">Theft Protection</li>
            </ul>
    </article>

    <h2>Filters</h2>

    <h4>Doors:</h4> 
    <select data-ng-model="search.carDetails">
        <option value="">All</option>
        <option value="2">2</option>
        <option value="4">4</option>
        <option value="9">9</option>
    </select>

    <h4>Provider:</h4>
    Atlas Choice <input type="checkbox"  data-ng-model="search.company" ng-true-value="Atlas Choice" ng-false-value="" value="Atlas Choice" /><br>
    Holiday Autos <input type="checkbox"  data-ng-model="search.company" ng-true-value="Holiday Autos" ng-false-value="" value="Holiday Autos" /><br>
    Avis <input type="checkbox"  data-ng-model="search.company" ng-true-value="Avis" ng-false-value="" value="Avis" /><br>      

이제 컨트롤러에서 ng-repeat의 항목을 반복하고 특정 기준을 충족하는 항목 만 반환 할 수있는 사용자 지정 필터를 만들고 싶습니다. 예를 들어 '제공자'확인란을 기반으로 값 배열을 만들 수 있습니다. 확인한 다음 각 ng-repeat 항목을 이에 대해 평가합니다. 구문 측면에서 어떻게 할 수 있는지 알 수는 없습니다. 누구나 도울 수 있습니까?

내 Plunker는 다음과 같습니다 : http://plnkr.co/edit/lNJNYagMC2rszbSOF95k?p=preview


일부 사용자 지정 필터 논리를 실행하려면 배열 요소를 인수로 사용하여 반환 true하거나 false검색 결과에 있어야하는지 여부를 기반으로 하는 함수를 만들 수 있습니다 . 그런 다음 객체에 대해 filter수행 한 것처럼 명령에 전달합니다 search. 예를 들면 다음과 같습니다.

JS :

$scope.filterFn = function(car)
{
    // Do some tests

    if(car.carDetails.doors > 2)
    {
        return true; // this will be listed in the results
    }

    return false; // otherwise it won't be within the results
};

HTML :

...
<article data-ng-repeat="result in results | filter:search | filter:filterFn" class="result">
...

보시다시피 많은 필터를 함께 연결할 수 있으므로 사용자 정의 필터 기능을 추가해도 search개체를 사용하여 이전 필터를 제거하지 않아도 됩니다 (매끄럽게 함께 작동합니다).


사용자 지정 필터가 필요한 경우 검색 모델을 필터에 전달할 수 있습니다.

<article data-ng-repeat="result in results | cartypefilter:search" class="result">

cartypefilter에 대한 정의는 다음과 같습니다.

app.filter('cartypefilter', function() {
  return function(items, search) {
    if (!search) {
      return items;
    }

    var carType = search.carType;
    if (!carType || '' === carType) {
      return items;
    }

    return items.filter(function(element, index, array) {
      return element.carType.name === search.carType;
    });

  };
});

http://plnkr.co/edit/kBcUIayO8tQsTTjTA2vO?p=preview


동일한 ng-repeat 필터에서 1 개 이상의 함수 필터를 호출 할 수 있습니다.

<article data-ng-repeat="result in results | filter:search() | filter:filterFn()" class="result">

One of the easiest ways to fix this is to use the $ which is the search all.

Here is a plunker that shows it working. I have changed the checkboxes to radio ( because I thought they should be complementary )..

http://plnkr.co/edit/dHzvm6hR5P8G4wPuTxoi?p=preview

If you want a very specific way of doing this ( instead of doing a generic search ) you need work with functions in the search.

The documentation is here

http://docs.angularjs.org/api/ng.filter:filter

참고URL : https://stackoverflow.com/questions/16563018/angularjs-custom-filters-and-ng-repeat

반응형