angularjs 过滤多个表达式 [英] angularjs filtering multiple expressions

查看:26
本文介绍了angularjs 过滤多个表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angularjs 的新手,只是想要一些过滤方面的帮助...

I am new to angularjs and just wanted some help with filtering...

我了解过滤的基础知识(这是非常基础的),但我想做的是使用多个表达式进行过滤.

I understand the basics of filtering (which is very basic) but what I want to do is filter using multiple expressions.

HTML:

<body data-ng-init="phones = [{make:'Apple', model:'iPhone5'}, {make:'HTC', model:'One'}, {make:'Samsung', model:'GalaxyS4'}]">
    <p>my first angular app</p>
    <p><label>filter</label><input data-ng-model="phoneFilter.$" type="text"></p>
    <ul>
        <li data-ng-repeat="phone in phones | filter:phoneFilter">
            {{phone.make}} {{phone.model}} 
        </li>
    </ul>
</body>

现在,如果我过滤apple"iphone5",它可以正常工作,但如果我在开始输入型号后立即输入apple i",则过滤器为空白.

Now if i filter 'apple' or 'iphone5' it works fine but if i type 'apple i' as soon as i start typing the model the filter is blank.

我需要为此创建自定义过滤器吗?

Do I need to create a custom filter for this?

干杯

推荐答案

至少你不能简单地使用过滤器的基本形式filter,因为 AngularJS 无法单独猜测一个空格表示或".

At least you can't simply use the basic form of the filter filter, because AngularJS can't guess alone that a space mean "or".

但是您不需要创建自己的指令.AngularJS 1.1.5 为 filter 提供了第三个参数(参见 文档).它可以采用一个函数,该函数将给出要比较的对象值和谓词值,如果该项目应包含在过滤结果中,则应返回 true".然后,您所要做的就是:

But you don't need to create your own directive. AngularJS 1.1.5 provides a third parameter for filter (see the documentation). It can take a function, which "will be given the object value and the predicate value to compare and should return true if the item should be included in filtered result". Then, all you have to do is:

$scope.multipleChoicesComparator = function (expected, actualInCompactForm)
{
    // Get a list of predicates
    var listActual = actualInCompactForm.split(' ');
    var mustBeIncluded = false;

    angular.forEach(listActual, function (actual)
    {
        // Search for a substring in the object value which match
        // one of the predicate, in a case-insensitive manner
        if (angular.lowercase(expected).indexOf(angular.lowercase(actual)) !== -1)
        {
            mustBeIncluded = true;
        }
    });

    return mustBeIncluded;
};

<li data-ng-repeat="phone in phones | filter:phoneFilter:multipleChoicesComparator">
    {{phone.make}} {{phone.model}} 
</li>

小提琴

这篇关于angularjs 过滤多个表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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