0

So I have an associative array (or object to be more precise)

$scope.items = { 'x': {...}, 'y': {...} };

I want to do an ng-repeat which works fine

<div ng-repeat="(id, data) in items | filter: customFunction" >

However the filter doesn't seem to be working, its defined as

$scope.customFunction = function (item) { return item.status === 'active'; }

However the filter is not working. I always get the whole set independently of what the filter is. Calling an alert inside the filter controller doesn't even show up. Seems like the function is not being called at all.

Before I was iterating through an array and it was working fine:

$scope.items = [ {...}, {...} ];
<div ng-repeat="item in items | filter: customFunction" >

I didn't include my logic for simplicity, I have some filtering logic rather than just return false.

2
  • so you are asking us to troubleshoot a function which you won't list the contents of to identify why it isn't returning false? Commented Nov 25, 2014 at 23:18
  • 1
    Thats not the problem. The problem is that it should simply return an empty subset and Im getting the whole subset. Its simply not filtering independently of the logic in it. Commented Nov 25, 2014 at 23:23

2 Answers 2

3

The issue here is that you no longer have an array of object, you have an object with properties, which the built in filter process cannot iterate through. Your filter will need to manually convert the object back to an array before it can filter it. The side effect here is that you will lose access to the id property in the ng-repeat as a result.

Before any filter logic, you would need to populate a standard array with the items object.

A filter to perform the logic you posted I would do like so:

app.filter('customFunction', function(){
    return function (items) { 
        var filtered = [];
        angular.forEach(items, function(item){
            if item.status === 'active';
            filtered.push(item);
        });
        return filtered;
    };
});

<div ng-repeat="item in items | customFunction" >
Sign up to request clarification or add additional context in comments.

Comments

2

Thanks Andrew for your suggestion, thats definitely the problem I was having. I came across a more generic solution in case someone wants to use it:

app.filter('filterObject', function() {
    return function(items, callback) {
        var filtered = {};

        angular.forEach(items, function(item, key) {
            if (callback(item)) {
                filtered[key] = item;
            }
        });

        return filtered;
    };
});

Then you use it as

item in items | filterObject:<customFunction>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.