Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat filter "show all" items if no filter selected

Tags:

angularjs

I have an ng-repeat filter that uses a <select> menu to filter through a bunch of countries.

For example:

<div class="col-md-3 col-sm-6" ng-repeat="item in listings | filter: { location: locationFilter }">

How can I make it so that if nothing is selected, it automatically shows ALL the countries? And only starts filtering once a particular country is selected?

I'm sure this is probably a simple question but I am quite new to this and couldn't find how to do it.

Thanks!

like image 231
KriiV Avatar asked Jan 27 '15 06:01

KriiV


People also ask

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

How do you put filters on NG-repeat?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

What does ng-repeat do?

The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

Where is the last element in NG-repeat?

$first and $last It's common when using ng-repeat to add specific behavior to the first or last element of the loop, e.g. special styling around the edges. Instead, ng-repeat already supplies you with two ready boolean properties. $first is true for the first element, and $last is true for the last element.


1 Answers

If the filter expression returned undefined, then the filter would not apply. So, you could do something like the following:

<div ng-repeat="item in listings | filter:(!!locationFilter || undefined) && {location: locationFilter}">
   {{item}}
</div>

(!!locationFilter handles '', falsy and undefined values)

plunker

like image 150
New Dev Avatar answered Nov 16 '22 00:11

New Dev