Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular material autocomplete search anywhere in string?

https://material.angularjs.org/latest/#/demo/material.components.autocomplete

Please can someone tell me how to make autocomplete (Angular material) to search string not only at the beginning of words, but anywhere within the words.

For example the word Alabama: Works when you type "Ala", but does not work when you type "bama". How do I make it to work when I type "bama"?

I know I can use a third party directive such as Angucomplete Alt: http://ghiden.github.io/angucomplete-alt/ but I think Angular material should have this option?

like image 344
Toni Kutlic Avatar asked Sep 15 '15 14:09

Toni Kutlic


2 Answers

This is a function from the original md-autocomplete:

function createFilterFor(query) {
  var lowercaseQuery = angular.lowercase(query);
  return function filterFn(state) {
    return (state.value.indexOf(lowercaseQuery) === 0);
  };
}

Please try changing the condition a little bit, like this:

    return (state.value.indexOf(lowercaseQuery) >= 0);

and it should work the way you want.

like image 103
bosskovic Avatar answered Dec 03 '22 05:12

bosskovic


The demo only matches characters at the beginning of the result due to specifying the caret flag, ie: md-highlight-flags="^i"

To allow autocomplete to find any matching characters you should use the global flag, ie: md-highlight-flags="gi"

You will also need to change the state.value.indexOf(lowercaseQuery) === 0 line in the filterFn function to state.value.indexOf(lowercaseQuery) !== -1

Check this codepen for a working example: http://codepen.io/DevVersion/pen/KrOYoG

like image 37
Bit32 Avatar answered Dec 03 '22 05:12

Bit32