5

I want to reset <md-autocomplete> control in Material AngularJS.

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

Basically I want to reset it to it's initial state. I can access ng-model & assign null to it. But, it doesn't remove the displayed text contained in md-item-text attribute.

Can please someone let me know how can I solve the same.

user2538076
  • 173
  • 1
  • 2
  • 18

3 Answers3

5

You need to clear the search text, have a look at this codepen: http://codepen.io/anon/pen/QbGZWP?editors=101

I created a button that calls the clear function:

function clear() {
  self.selectedItem = null;
  self.searchText = "";
}

These are the attributes set on the md-autocomplete directive:

<md-autocomplete 
  md-selected-item="ctrl.selectedItem" 
  md-search-text="ctrl.searchText" 
  md-items="item in ctrl.querySearch(ctrl.searchText)" 
>

Note: You might need the other attributes too, depends on your case.

Belicosus
  • 302
  • 1
  • 7
  • 1
    your solution works, when clear() is invoked by ng-click.. but it doesn't work when called from inside a function invoked by `md-selected-item-change` – Lloyd Jun 09 '15 at 14:19
  • @Lloyd: Works as expected. Edited the codepen: http://codepen.io/anon/pen/vOmqwv?editors=101 – Belicosus Jun 09 '15 at 18:30
  • https://codepen.io/anon/pen/vdbpYv?editors=1010 ..md-autocomplete reset is not working – its me Mar 01 '18 at 06:11
  • https://codepen.io/anon/pen/vdbpYv?editors=1010 ..md-autocomplete reset is not working – its me Mar 01 '18 at 06:12
  • Works amazingly, thank you. Spent a half a day to resolve this, until I've found your answer. Big vote up! – Fery Kaszoni Apr 21 '18 at 14:31
2

you may use md-selected-item-change to handle this. for example

    <md-autocomplete flex
       md-item-text="item.Text"
       md-items="item in data"
       md-search-text-change="query(searchText)"
       md-search-text="searchText"
       md-selected-item="selectedItem"
       md-no-cache="false"
       md-input-minLength="2"
       md-input-name="exampleAutocomplete"
       md-selected-item-change="addSelectedItem();"
       md-floating-label="Nereye">
           <md-item-template>
               <span md-highlight-text="searchText">{{item.Text}}</span>
           </md-item-template>
           <md-not-found>No matching were found were "{{searchText}}".</md-not-found>
    </md-autocomplete>

and your controller side, you must define a function with name "addSelectedItem" and assign searchText with an empty string. like;

$scope.addSelectedItem = function () {
            $scope.searchText = ''; 
};

it works for me. hopefully it will help you to solve your problem.

Vecihi Baltacı
  • 352
  • 4
  • 20
0

Set md-min-length="1" would make the clear work without extra clear function or button.

Lin Song Yang
  • 1,936
  • 19
  • 17