Angular filter list without ng-repeat

浪尽此生 提交于 2019-11-30 00:52:49

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

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!

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;
}

you can make it as Michel Tome wrote just more generic 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 the 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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!