snaggs snaggs - 4 months ago 424
AngularJS Question

Angular Material: md-autocomplete - how to hide md-autocomplete-suggestions on Enter event?

I have

md-autocomplete
:

<md-autocomplete
md-min-length="1"
ng-enter="presEnter();"
md-no-cache="true"
md-selected-item="selectedItem"
md-search-text="searchText"
md-items="item in querySearch(searchText)"
md-item-text="item.name"
placeholder="Search for a vegetable">
<span md-highlight-text="searchText">{{item.name}} :: {{item.type}}</span>
</md-autocomplete>


with directive:
ng-enter
.

My goal: When user presses
Enter
I want to hide
md-autocomplete-suggestions
dropdown


I know from HTML I need somehow to call:
$mdAutocompleteCtrl.hidden = true;
but have no idea how to use
$mdAutocompleteCtrl
in Controller.

I googled and found:

$timeout( function() { $scope.$$childHead.$mdAutocompleteCtrl.hidden = true; },100);


but there is no
$mdAutocompleteCtrl
(at least in my JS, only in HTML and i don't know its scope)

I play with this example: type 'a' and after dropdown press Enter.

Any ideas?

Answer

The $mdAutocompleteCtrl is placed as a property on the autocomplete's scope.

First, you need access to the autocomplete element. One way to do that is to put an ID on the autocomplete:

<md-autocomplete id='Auto'
                 md-min-length="1"
                 ng-enter="presEnter();"
                 md-no-cache="true"
                 md-selected-item="selectedItem"
                 md-search-text="searchText"
                 md-items="item in querySearch(searchText)"
                 md-item-text="item.name"
                 placeholder="Search for a vegetable">

Then you can use that element to get the inner scope of the autocomplete. Because the autocomplete element itself is on the scope that you provided, you'll want to get the scope of one of the autocomplete's child elements.

$scope.presEnter = function(e){
    var autoChild = document.getElementById('Auto').firstElementChild;
    var el = angular.element(autoChild);
    el.scope().$mdAutocompleteCtrl.hidden = true;
};

Here is a working example: http://codepen.io/anon/pen/rVPZKN?editors=101

Comments