3

I am new to angularjs and just wanted some help with filtering...

I understand the basics of filtering (which is very basic) but what I want to do is filter using multiple expressions.

HTML:

<body data-ng-init="phones = [{make:'Apple', model:'iPhone5'}, {make:'HTC', model:'One'}, {make:'Samsung', model:'GalaxyS4'}]">
    <p>my first angular app</p>
    <p><label>filter</label><input data-ng-model="phoneFilter.$" type="text"></p>
    <ul>
        <li data-ng-repeat="phone in phones | filter:phoneFilter">
            {{phone.make}} {{phone.model}} 
        </li>
    </ul>
</body>

Now if i filter 'apple' or 'iphone5' it works fine but if i type 'apple i' as soon as i start typing the model the filter is blank.

Do I need to create a custom filter for this?

Cheers

1 Answer 1

2

At least you can't simply use the basic form of the filter filter, because AngularJS can't guess alone that a space mean "or".

But you don't need to create your own directive. AngularJS 1.1.5 provides a third parameter for filter (see the documentation). It can take a function, which "will be given the object value and the predicate value to compare and should return true if the item should be included in filtered result". Then, all you have to do is:

$scope.multipleChoicesComparator = function (expected, actualInCompactForm)
{
    // Get a list of predicates
    var listActual = actualInCompactForm.split(' ');
    var mustBeIncluded = false;

    angular.forEach(listActual, function (actual)
    {
        // Search for a substring in the object value which match
        // one of the predicate, in a case-insensitive manner
        if (angular.lowercase(expected).indexOf(angular.lowercase(actual)) !== -1)
        {
            mustBeIncluded = true;
        }
    });

    return mustBeIncluded;
};
<li data-ng-repeat="phone in phones | filter:phoneFilter:multipleChoicesComparator">
    {{phone.make}} {{phone.model}} 
</li>

Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but as soon as i type the 'i' in iphone (after typing apple) it vanishes from filtered results still.
It doesn't, just try the Fiddle. But the third parameter of the filter filter was introduce in AngularJS 1.1.3, so be sure to use at least this version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.