Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
707 views
in Technique[技术] by (71.8m points)

angularjs filtering multiple expressions

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...