没有 ng-repeat 的角度过滤器列表 [英] Angular filter list without ng-repeat

查看:24
本文介绍了没有 ng-repeat 的角度过滤器列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么好方法可以使用 angular 过滤列表而不使用 ng-repeat?一开始我不想使用javascript来绘制列表,但我想在之后使用angular来过滤它.

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.

示例:

<input type="search" ng-model="search" placeholder="Search for fruits!" />

<ul>
  <li>Banana</li>
  <li>Apple</li>
  <li>Orange</li>
</ul>

我想使用搜索框来过滤现有的 html.

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

(请不要举任何 ng-repeat 或 jQuery 的例子)

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

推荐答案

您可以编写一个简单的指令来处理显示/隐藏:

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

并以这种方式使用它:

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

使用指令有几个好处:

1).您不必在每个 li 上放置任何 ngShow/ngIf 指令.

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

2).它还可以使用新的附加 li 元素到列表中.

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

这篇关于没有 ng-repeat 的角度过滤器列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆