Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS filter is not working for multiple words from 2 different keys

This is some of sample JSON data.

$scope.Products = [
{
    "Variants": [],
    "SubCategoryID": "66",
    "ProductImagePath": "/images/britannia/887.png",
    "SubCategoryName": "Butter",
    "BrandName": "Britannia",
    "ProductID": "887",
    "BrandID": "76",
    "ProductName": "Butter"
},
{
    "Variants": [],
    "SubCategoryID": "71",
    "ProductImagePath": "/images/amul/886.png",
    "SubCategoryName": "Cheese",
    "BrandName": "Amul",
    "ProductID": "886",
    "BrandID": "47",
    "ProductName": "cheese"
},
{
    "Variants": [],
    "SubCategoryID": "106",
    "ProductImagePath": "/images/amul/885.png",
    "SubCategoryName": "Curd",
    "BrandName": "Amul",
    "ProductID": "885",
    "BrandID": "47",
    "ProductName": "curd"
}
]

And this is How i am rendering to webpage.

<div ng-if="SearchText" class='box' ng-repeat="product in Products | filter:FilterExpr | orderBy:'ProductName'">
    <ng-include src="'commonTemplate.html'"></ng-include>
</div>

There is a search text box in page. When user start typing in serach text box i assigns value to FilterExpr like this.

$scope.$on('SearchTextChanged', function(event, SearchText) {

    if (SearchText.length >=3)  {
        $scope.FilterExpr = SearchText;
    }
});

When user type amul or cheese or butter, It is able to filter the products. Problem is when user types amul curd or curd amul or butter britannia, NO products are displaying on the page.

How to make it work? What change i need to do to so it is able to filter for multiple words.

like image 869
Devesh Agrawal Avatar asked Jul 02 '15 16:07

Devesh Agrawal


1 Answers

The default comparator used by the default filter is very simple. It looks for the exact searched string and does not parse the search string in any way. The simplest way to improve this is implementing another comparator (doc).

<div ng-if="SearchText" class='box' ng-repeat="product in Products | filter:FilterExpr:searchFuncComparator | orderBy:'ProductName'">
   <ng-include src="'commonTemplate.html'"></ng-include>
</div>

and adding a comparator to the $scope:

$scope.searchFuncComparator = function(actual, expected) {
    // compare actual with expected and return true if match
    // otherwise false
};

All there is left is to implement you're favorite search method above :)

like image 156
Emil Ingerslev Avatar answered Nov 12 '22 19:11

Emil Ingerslev