Search code examples
javascriptangularjsangular-strap

ngstrap typeahead unordered multiple keyword search


I having an issue with ngstrap typeahead with the scenario below:

var companyItem= [
 {
"item_id": 1,
"item_name": "mobile phone middle nokia",
"company_id": 1,

},
{
"item_id": 2,
"item_name": "mobile phone iphone",
"company_id": 1,

},
{
"item_id": 8,
"item_name": "mobile phone samsung",
"company_id": 1,

},
{
"item_id": 9,
"item_name": "apple watch",
"company_id": 1,

}
]

My Markup :

<input type="text" class="form-control" name="itemName" id="itemName" ng-model="item.itemName" data-min-length="0" bs-options="item as item.item_name for item in companyItem | filter:{item_name:$viewValue}:customCompare" bs-typeahead="setCustomerData" data-watch-options="true" data-container="body" autocomplete="off" ng-readonly="readOnly" required>

and my scripts is :

$scope.customCompare = function(itemName, viewValue) {
    var keyword = viewValue.split(" ");
    var partialMatch = false;

    for(var i=0;i<keyword.length;i++){
          console.log('keyword'+i+' '+keyword[i]);
            console.log('itemName '+itemName);
            console.log('keyword[i].indexOf(itemName) > -1 '+itemName.indexOf(keyword[i].toString()));
            if(itemName.indexOf(keyword[i].toString()) > -1){
               console.log(' <<>>---------------');
                partialMatch =true;

            }       

    }
       return partialMatch;
}

I've try to search with keyword 'mobile iphone' in the input text but there're no result.

This return true as I'm write in the console log but the record not showing

Anyway if 'phone iphone' it's working like default typeahead

Anything I'm done wrong or this approach is not working

https://plnkr.co/edit/3iJwREetLMnTup24Sbtd

Thanks in Advance.


Solution

  • Ng-strap adds a default filter that uses a default comparator after your item as item.item_name for item in companyItem | filter:{item_name:$viewValue}:customCompare.

    One hacky solution is to bypass the default filter.

    $scope.alwaysTrue = function() { return true; }
    <input ... bs-options="item as item.item_name for item in companyItem | filter:{item_name:$viewValue}:customCompare" data-comparator="alwaysTrue" ...>

    A cleaner solution would be to set data-comparator="customCompare". Sadly, that doesn't work because here contains :$viewValue, not :{item_name: $viewValue}. So, customCompare never gets to process a whole object.

    The API can and should be improved, and you should open an issue about it on github.