在 AngularJS 中按多个特定模型属性过滤(在 OR 关系中) [英] Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

查看:25
本文介绍了在 AngularJS 中按多个特定模型属性过滤(在 OR 关系中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看这里的例子:http://docs.angularjs.org/api/ng.filter:filter

您可以使用 <input ng-model="search"> 搜索任何手机属性,也可以使用 <input ng 仅搜索名称-model="search.name">,结果按名称进行适当过滤(输入电话号码不会返回任何结果,正如预期的那样).

You can search by any of the phone properties by using <input ng-model="search"> and you can search by just the name by using <input ng-model="search.name">, and the results are appropriately filtered by name (typing in a phone number does not return any results, as expected).

假设我有一个具有名称"属性、电话"属性和秘密"属性的模型,我将如何通过两个名称"和电话"属性和不是秘密"属性?所以本质上,用户可以输入姓名或电话号码,ng-repeat 将正确过滤,但即使用户输入的值等于秘密"值的一部分,它也不会不返回任何东西.

Let's say I have a model with a "name" property, a "phone" property, and a "secret" property, how would I go about filtering by both the "name" and "phone" properties and not the "secret" property? So in essence, the user could type a name or phone number and the ng-repeat would filter correctly, but even if the user typed in a value that equaled part of a "secret" value, it wouldn't return anything.

谢谢.

推荐答案

这里是 plunker

新的 plunker 代码更简洁 &其中查询和搜索列表项都不区分大小写

主要思想是创建一个过滤函数来实现这个目的.

Main idea is create a filter function to achieve this purpose.

来自官方文档

function:谓词函数可用于编写任意过滤器.为数组的每个元素调用该函数.最终结果是谓词返回 true 的那些元素的数组.

function: A predicate function can be used to write arbitrary filters. The function is called for each element of array. The final result is an array of those elements that the predicate returned true for.

<input ng-model="query">

<tr ng-repeat="smartphone in smartphones | filter: search "> 

$scope.search = function(item) {
    if (!$scope.query || (item.brand.toLowerCase().indexOf($scope.query) != -1) || (item.model.toLowerCase().indexOf($scope.query.toLowerCase()) != -1) ){
        return true;
    }
    return false;
};

更新

有些人可能会担心现实世界中的性能,这是正确的.

Some people might have a concern on performance in real world, which is correct.

在现实世界中,我们可能会从控制器进行这种过滤.

In real world, we probably would do this kinda filter from controller.

这是详细帖子,展示了如何去做.

Here is the detail post showing how to do it.

简而言之,我们在 input 中添加 ng-change 以监控新的搜索变化

in short, we add ng-change to input for monitoring new search change

然后触发过滤功能.

这篇关于在 AngularJS 中按多个特定模型属性过滤(在 OR 关系中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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