10

I have a dialog with few field to set, the first field is a md-autocomplete, when I click ok all these fields are cleaned, so, I want set focus true in the md-autocomplete, for starting to filling data again.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
mos
  • 337
  • 2
  • 4
  • 11

2 Answers2

12

Try this :

JS:

$scope.setFocus = function() {
  setTimeout(function() {
    document.querySelector('#autoCompleteId').focus();
  }, 0);
}

HTML:

<md-autocomplete .............. md-input-id="autoCompleteId">
  <!-- Note the id -->
</md-autocomplete>

<input type="button" value="clickMeForFocus" ng-click="setFocus()" />

The timeout is needed to make sure that the autocomplete component is rendered at the time of calling focus.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Rambler
  • 4,994
  • 2
  • 20
  • 27
6

You can do that by adding attribute

md-autofocus

an example:

<md-autocomplete md-autofocus md-selected-item="selectedItem" md-search-text="searchText" md-items="item in getMatches(searchText)" md-item-text="item.display">
    <span md-highlight-text="searchText">{{item.display}}</span>
</md-autocomplete>

ref : here

Regards.

Hardik Vaghani
  • 2,163
  • 24
  • 46
  • 1
    That works for first time that dialog is opened, when click ok, and data are cleaned, focus is lost and md-autofocus does not work. I have this solution, when dialog is hidden, I call this document.getElementById('product-name-input').querySelector('input').focus(); – mos Jun 15 '16 at 05:45