正是角上过滤对象键 [英] Angular filter exactly on object key

查看:103
本文介绍了正是角上过滤对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个小角度的应用程序,像这样:

Hi I have a small angular app like so:

HTML

<body ng-app>
  <div ng-controller="Ctrl">
    <div ng-repeat="user in users | filter:1">
      <span>{{ user.username }}, {{ user.id }}</span>
    </div>
  </div>
</body>

app.js

function Ctrl($scope) {
  $scope.users = [
    {"id":1,"username":"simon",},
    {"id":8,"username":"betty",},
    {"id":14,"username":"archie",},
    {"id":3,"username":"jumbo1"},
  ]
}

输出

simon, 1
archie, 14
jumbo1, 3

我想要做的是一个过滤的确切的匹配上id字段过滤器参数和过滤器只。

What I want to do is filter an exact match for filter argument AND filter on the id field ONLY.

基本上,我想输出是:

输出

simon, 1

我用的1.2角,但我难倒如何得到确切的功能,我需要。

I am using Angular 1.2, but I'm stumped as to how to get the exact functionality I need.

任何帮助将是非常美联社preciated。

Any help would be much appreciated.

推荐答案

在角1.1.3或更高版本,您可以使用以下内容:

In Angular 1.1.3 or newer you can use the following:

<div ng-repeat="user in users | filter:{'id':  1}:true">

{ID:1} 表示,只与该领域比较 ID 。这可以让你:

{'id': 1} says to only compare with the field id. That gets you:

simon, 1
archie, 14

:真​​正的说:精确匹配造成:

simon, 1

下面是一个工作: http://jsfiddle.net/AM95H/

要筛选抗值的列表,如果你在一个范围内的变量列表中,我自定义过滤器添加到您的JS文件:

To filter against a list of values, if you have the list in a scope variable, I'd add a custom filter to your JS file:

$scope.filterValues = [1,8];
$scope.myFilter = function(value) {
   return ($scope.filterValues.indexOf(value.id) !== -1);
};

用于这样的:

<div ng-repeat="user in users |  filter: myFilter">

要过滤针对参数列表:我们将创建自己的过滤器。在这种情况下,我们会得到所有的输入值调用一次测试,而不是每一次的价值。

To filter against a parameter list we'll create our own filter. In this case we'll get called once with all the input values to test rather than once per value.

因此​​,我们将收到第一个参数是输入值(在你的情况下,用户),第二个参数是我们传递的参数数组([1,8])。然后,我们将创建一个输出数组,并添加(推)的输入流中匹配的 filterValues​​ 一个任何项目。并返回输出数组。

So the first parameter we'll receive is the array of input values (users in your case) and the second parameter will be the parameter we pass in ([1,8]). We'll then create an output array and add (push) any items in the input stream that match one of the filterValues. And return the output array.

myApp.filter('myFilter', function () {  
   return function(inputs,filterValues) {
      var output = [];
      angular.forEach(inputs, function (input) {
        if (filterValues.indexOf(input.id) !== -1)
            output.push(input);
       });
       return output;
   };
});

和使用这样的:

<div ng-repeat="user in users |  myFilter:[1,8]">

下面就是一个这样的例子: http://jsfiddle.net/AM95H/2/

Here's an example of this: http://jsfiddle.net/AM95H/2/

这篇关于正是角上过滤对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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