Cecil Theodore
Cecil Theodore

Reputation: 9939

How to use an OR in a filter AngularJS

I have an unordered list that is being filtered on when a select option is selected. My problem is that when 'ALL' is selected nothing displays because the value does not match the item.status of any of my list items. Is there a way of adding || which will then filter on item.status or 'ALL'?

Below are the values that are in the select. One of these values is also referenced for each list item as item.status

app.value('filterSavedList', pageOptions = [
    {
        value: 'ALL',
        label: 'All'
    },
    {
        value: 'NEW',
        label: 'Not started'
    },
    {
        value: 'STARTED',
        label: 'In progress'
    },
    {
        value: 'COMPLETED',
        label: 'Completed'
    }
]);

My select and my unordered list.

    <select ng-model="filter" ng-options="item.value as item.label for item in status">
    </select>

<ul>
    <li ng-repeat="item in assignments | filter: { status : filter }">
       //do stuff                     
    </li>
</ul>

Upvotes: 0

Views: 41

Answers (2)

JB Nizet
JB Nizet

Reputation: 691755

You simply need to set the status value to '' (empty string), and make sure filter (i.e. the model of the select box) is initialized to one of the 4 values (i.e. initialized to '', if the option All must be pre-selected)

See http://plnkr.co/edit/mJtQnwA3aQhpT4WN62jj?p=preview for a complete example.

Upvotes: 1

pgrodrigues
pgrodrigues

Reputation: 2078

You can also create a custom filter that does normal filtering by property and also takes care of the ALL possibility in status:

.filter('filterStatus', function () {
    return function (items, status) {
        if(status === 'ALL') {
            return items;
        }
        else {
            var itemsToReturn = [];
            for(var i=0,x=items.length;i<x;i++) {
                if(items[i].status === status) {
                    itemsToReturn.push(items[i]);
                }
            }
            return itemsToReturn;
        }
    };
});

Then in HTML:

<ul>
    <li ng-repeat="item in assignments | filterStatus: filter">
        <!-- do stuff -->                     
    </li>
</ul>

Upvotes: 1

Related Questions