How to filter (key, value) with ng-repeat in AngularJs?
Asked Answered
G

8

116

I am trying to do something like :

<div ng-controller="TestCtrl">
    <div ng-repeat="(k,v) in items | filter:hasSecurityId">
        {{k}} {{v.pos}}
    </div>
</div>

AngularJs Part:

function TestCtrl($scope) 
{
    $scope.items = {
                     'A2F0C7':{'secId':'12345', 'pos':'a20'},
                     'C8B3D1':{'pos':'b10'}
                   };

    $scope.hasSecurityId = function(k,v)
    {
       return v.hasOwnProperty('secId');
    }
}

But somehow, it is showing me all items. How can I filter on (key,value) ?

Gutsy answered 9/2, 2013 at 13:25 Comment(4)
please provide some example data fot items. Or give us a fiddle ;)Carrion
This is not how you create a filter look at the documentations, and as Robin said, an example please.Limulus
I already gave a full example and I know how to use filters. I am just asking "how to use filter with (key,value)".Gutsy
index and count should be available in that scope iircAstarte
H
132

Angular filters can only be applied to arrays and not objects, from angular's API -

"Selects a subset of items from array and returns it as a new array."

You have two options here:
1) move $scope.items to an array or -
2) pre-filter the ng-repeat items, like this:

<div ng-repeat="(k,v) in filterSecId(items)">
    {{k}} {{v.pos}}
</div>

And on the Controller:

$scope.filterSecId = function(items) {
    var result = {};
    angular.forEach(items, function(value, key) {
        if (!value.hasOwnProperty('secId')) {
            result[key] = value;
        }
    });
    return result;
}

jsfiddle: http://jsfiddle.net/bmleite/WA2BE/

Highbrow answered 9/2, 2013 at 14:46 Comment(6)
One needs to be careful with this approach to avoid infinite (digest) loops. See 6054 and 705. Summary by Narretz: In short, using functions to return the collection in ng-repeat is an anti-pattern. It's better to assign the collection to a scope property, and loop over that.Prospect
Helpful comment. This was throwing me for a loop; I expected to be able to filter any iterable. Thanks much. :)Grumous
Note: This is a perf anti-pattern now. Angular 1.3 has stateless filters now (egghead.io/lessons/…) so you'd definitely want to create a filter for this.Cundiff
@Cundiff don't post links which are not free!Indebted
@Sebastian, sorry about that. But there are people who are egghead.io subscribers and I expect it's useful to them.Cundiff
Why not just add an ng-if on the repeated element?Briannebriano
P
46

My solution would be create custom filter and use it:

app.filter('with', function() {
  return function(items, field) {
        var result = {};
        angular.forEach(items, function(value, key) {
            if (!value.hasOwnProperty(field)) {
                result[key] = value;
            }
        });
        return result;
    };
});

And in html:

 <div ng-repeat="(k,v) in items | with:'secId'">
        {{k}} {{v.pos}}
 </div>
Photoflash answered 9/2, 2013 at 16:13 Comment(1)
however, it will loop n*n times.Obadiah
A
34

Also you can use ng-repeat with ng-if:

<div ng-repeat="(key, value) in order" ng-if="value > 0">
Aesculapian answered 9/12, 2015 at 22:16 Comment(1)
Clever. This saved a lot of time.Plasterboard
C
21

Or simply use

ng-show="v.hasOwnProperty('secId')"

See updated solution here:

http://jsfiddle.net/RFontana/WA2BE/93/

Chemmy answered 22/10, 2013 at 14:7 Comment(1)
Thanks.. I used this but with ng-if insteadTinfoil
S
11

You can simply use angular.filter module, and then you can filter even by nested properties.
see: jsbin
2 Examples:

JS:

angular.module('app', ['angular.filter'])
  .controller('MainCtrl', function($scope) {
  //your example data
  $scope.items = { 
    'A2F0C7':{ secId:'12345', pos:'a20' },
    'C8B3D1':{ pos:'b10' }
  };
  //more advantage example
  $scope.nestedItems = { 
    'A2F0C7':{
      details: { secId:'12345', pos:'a20' }
    },
    'C8B3D1':{
      details: { pos:'a20' }
    },
    'F5B3R1': { secId:'12345', pos:'a20' }
  };
});

HTML:

  <b>Example1:</b>
  <p ng-repeat="item in items | toArray: true | pick: 'secId'">
    {{ item.$key }}, {{ item }}
  </p>

  <b>Example2:</b>
  <p ng-repeat="item in nestedItems | toArray: true | pick: 'secId || details.secId' ">
    {{ item.$key }}, {{ item }}
  </p> 
Secrest answered 6/10, 2014 at 13:29 Comment(2)
You should disclose that angular.filter is not a core angular module and you are the author of it.Cecilla
It looks like the toArray filter is not present anymore. Is there a replacement, because the filter filter still does not allow objects?Eugeneeugenia
M
7

It is kind of late, but I looked for e similar filter and ended using something like this:

<div ng-controller="TestCtrl">
 <div ng-repeat="(k,v) in items | filter:{secId: '!!'}">
   {{k}} {{v.pos}}
 </div>
</div>
Melchor answered 5/2, 2016 at 8:25 Comment(1)
How did you get this to work? When I use a filter with an ng-repeated object, I get an error which is what is expected base on the Angular documentation.Orel
E
1

Although this question is rather old, I'd like to share my solution for angular 1 developers. The point is to just reuse the original angular filter, but transparently passing any objects as an array.

app.filter('objectFilter', function ($filter) {
    return function (items, searchToken) {
        // use the original input
        var subject = items;

        if (typeof(items) == 'object' && !Array.isArray(items)) {
            // or use a wrapper array, if we have an object
            subject = [];

            for (var i in items) {
                subject.push(items[i]);
            }
        }

        // finally, apply the original angular filter
        return $filter('filter')(subject, searchToken);
    }
});

use it like this:

<div>
    <input ng-model="search" />
</div>
<div ng-repeat="item in test | objectFilter : search">
    {{item | json}}
</div>

here is a plunker

Embolic answered 9/11, 2017 at 11:51 Comment(0)
J
0

I made a bit more of a generic filter that I've used in multiple projects already:

  • object = the object that needs to be filtered
  • field = the field within that object that we'll filter on
  • filter = the value of the filter that needs to match the field

HTML:

<input ng-model="customerNameFilter" />
<div ng-repeat="(key, value) in filter(customers, 'customerName', customerNameFilter" >
   <p>Number: {{value.customerNo}}</p>
   <p>Name: {{value.customerName}}</p>
</div>

JS:

  $scope.filter = function(object, field, filter) {
    if (!object) return {};
    if (!filter) return object;

    var filteredObject = {};
    Object.keys(object).forEach(function(key) {
      if (object[key][field] === filter) {
        filteredObject[key] = object[key];
      }
    });

    return filteredObject;
  };
Jolt answered 15/6, 2017 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.