Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular filter list without ng-repeat

Is there any good way of using angular to filter a list WITHOUT ng-repeat? I dont want to use javascript to draw the list at first, but i want to use angular to filter it afterwards.

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 the existing html.

(Please dont give any examples with ng-repeat or jQuery in general)

like image 328
Jørgen Avatar asked Oct 28 '14 12:10

Jørgen


3 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 this way:

<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 a couple of benefits of using a directive:

1). You don't have to put any ngShow/ngIf directives on every li.

2). It will also work with a new appended li elements to the list.

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

like image 51
dfsq Avatar answered Nov 19 '22 07:11

dfsq


You could use ng-show/ng-hide and compare them to the value of the li's.

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's a lot easier with ng-repeat/filter!

like image 2
Michel Tomé Avatar answered Nov 19 '22 07:11

Michel Tomé


You could 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;
}
like image 1
Caleb Kiage Avatar answered Nov 19 '22 08:11

Caleb Kiage