Angular material autocomplete search anywhere in string?
Asked Answered
E

2

8

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?

Elate answered 15/9, 2015 at 14:1 Comment(0)
F
3

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

Forthright answered 27/1, 2017 at 14:32 Comment(1)
Do you know if Angular 2 has this md-highlight-flag?Pages
E
11

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.

Escargot answered 21/1, 2016 at 10:31 Comment(1)
how can you do that without changing the original source code?Hege
F
3

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

Forthright answered 27/1, 2017 at 14:32 Comment(1)
Do you know if Angular 2 has this md-highlight-flag?Pages

© 2022 - 2024 — McMap. All rights reserved.