Angular filter list without ng-repeat

Is there a good way to use angular to filter a list WITHOUT ng-repeat? I don't want to use javascript to draw a list first, but I want to use angular to filter it after.

Example:

<input type="search" ng-model="search" placeholder="Search for fruits!" /> <ul> <li>Banana</li> <li>Apple</li> <li>Orange</li> </ul> 

I want to use the search box to filter existing html.

(Please do not give any examples with ng-repeat or jQuery at all)

+7
javascript html angularjs angularjs-ng-repeat
source share
4 answers

You can write a simple directive to handle show / hide:

 app.directive('filterList', function($timeout) { return { link: function(scope, element, attrs) { var li = Array.prototype.slice.call(element[0].children); function filterBy(value) { li.forEach(function(el) { el.className = el.textContent.toLowerCase().indexOf(value.toLowerCase()) !== -1 ? '' : 'ng-hide'; }); } scope.$watch(attrs.filterList, function(newVal, oldVal) { if (newVal !== oldVal) { filterBy(newVal); } }); } }; }); 

and use it as follows:

 <input type="search" ng-model="search" placeholder="Search for fruits!" /> {{search}} <ul filter-list="search"> <li>Banana</li> <li>Apple</li> <li>Orange</li> </ul> 

There are several advantages to using the directive:

one). You do not need to specify ngShow/ngIf on every li .

2). It will also work with newly added li items to the list.

Demo: http://plnkr.co/edit/wpqlYkKeUTfR5TjVEEr4?p=preview

+12
source share

You can use ng-show / ng-hide and compare them with the li value.

Example:

 <input type="search" ng-model="search" placeholder="Search for fruits!" /> <ul> <li ng-show="matches('Banana')">Banana</li> <li ng-show="matches('Apple')">Apple</li> <li ng-show="matches('Orange')">Orange</li> </ul> 

And in your js:

 $scope.matches = function (text) { var pattern = new Regexp(text, "gi") return pattern.test($scope.search); } 

But this is just bad ... It is much easier with ng-repeat / filter!

+2
source share

You can do this using ngIf , ngShow or ngHide .

 <input type="search" ng-model="search" placeholder="Search for fruits!" /> <ul> <li ng-if="matches('Banana')">Banana</li> <li ng-if="matches('Apple')">Apple</li> <li ng-if="matches('Orange')">Orange</li> </ul> 
 $scope.matches = function(str) { return str.indexOf($scope.search) >= 0; } 
+1
source share

you can do this, since Michelle Tome wrote only a more general way.

 <input type="search" ng-model="search" placeholder="Search for fruits!" /> <ul> <li ng-show="isSimilar($event)">Banana</li> <li ng-show="isSimilar($event)">Apple</li> <li ng-show="isSimilar($event)">Orange</li> </ul> 

And in JS, take the text from the event.

 $scope.isSimilar = function ($event) { var text = $event.target.textContent; var pattern = new Regexp(text, "gi") return pattern.test($scope.search); } 
0
source share

All Articles