Reputation: 4022
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
Upvotes: 3
Views: 2414
Reputation: 20401
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>
Upvotes: 2