Multiple checkbox filtering in AngularJS

The first time I posted a question here, so I apologize in advance if I break the labels !:-)

The first time I study at AngularJS is to create a proof of concept for my boss. This is a basic car rental announcement, a list of results in the main column and a filter panel on the side. I managed to get the results from the JSON object and apply a basic filter, as shown below:

<article data-ng-repeat="result in results | filter:search" class="result"> <h3>{{result.carType.name}}, &pound;{{result.price.value}}</h3> <img class="car-type" alt="{{result.carType.name}}" src="{{result.carType.image}}" /> <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> 

Filters

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

... one thing that I have not been able to work out yet is how to add a group of flags to apply the filter, for example, "type of car", which will have options such as "mini", compact ',' family ', etc. .d. - and the user will be able to filter one or more parameters at a time. I know that I need to use "ng-model" and possibly "ng-change", I just don’t know how to apply it to a group of checkboxes ...?

Update . I created a plunker so you can see where I can: http://plnkr.co/edit/lNJNYagMC2rszbSOF95k?p=preview

+6
source share
2 answers

I would bind all the checkboxes to a single object:

app.js

 $scope.cartypes = {mini: false, compact:false}; 

index.html

 <input type="checkbox" data-ng-model="cartypes.mini"> Mini <input type="checkbox" data-ng-model="cartypes.compact"> Compact 

And then create a custom filter function that returns whether the object contains all (I assume you want) the checked parameters.

app.js

 app.filter('myfilter', function() { return function(items, options ) { // loop over all the options and if true ensure the car has them // I cant do this for you beacause I don't know how you would store this info in the car object but it should not be difficult return carMatches; }; }); 

Then you can add it to your template as follows:

index.html

 <article data-ng-repeat="result in results | filter:search | myfilter:cartypes" class="result"> 
+8
source

I implemented this solution as follows:

 @myapp.filter "storeFilter", -> (stores, type) -> _.filter stores, (store) -> type[store.name] 

and in the view I passed it like this:

 store in stores | storeFilter:store_type 
0
source

Source: https://habr.com/ru/post/944613/


All Articles