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

后端 未结 5 1972
旧时难觅i
旧时难觅i 2021-02-13 04:48

I have md-autocomplete:



        
相关标签:
5条回答
  • 2021-02-13 05:34

    I think this solution is better because:

    • it uses a directive instead of the controller.

    • it is simpler than the other given directive solution.

    Javascript

    app.directive('closeOnEnter', function($compile) {
          return {
             restrict: 'A',
             require: 'mdAutocomplete',
             link: function(scope, element) {
                element.on('keydown keypress', function($event) {
                   // 13: Enter
                   if ($event.keyCode == 13) {
                      var eAcInput = this.getElementsByTagName('input')[0];
                      eAcInput.blur();
                   }
                });
             },
          };
    });
    

    HTML

    <md-autocomplete close-on-enter ... ...>
    
    0 讨论(0)
  • 2021-02-13 05:37

    TLDR: Example code that triggers hide http://codepen.io/anon/pen/mJvGzp?editors=101

    The Problem(s):

    First off, the "Angular Way" suggests that manipulating directives in your Controller should be avoided. The Controller should essentially just retrieve (via Services, etc.) and provide the data required to build a view; it generally should avoid caring about exactly what how those views are implemented (i.e. it should know not what directives will be used). There are various good reasons for this, one might be that it makes life much easier when you want to modify the view, such as swapping out directives.

    If directives really need to be manually modified, it's better to do so from another directive. This allows more flexibility, and simplifies refactoring later (same example: if swapping out for different autocomplete directives).

    Also, although it seems to be the only way to solve the problem in this case, the $scope.$$childHead.$mdAutocompleteCtrl.hidden code seems fairly hacky - unless there is no other choice, one should avoid accessing properties starting with $$, and also avoid modifying sibling directives without doing so via shared scope properties.

    Unfortunately, after digging into the source code ( on the master branch ), I could not find any nicer way to trigger the hide function than (as you suggested) to grab it's scope and modify the hidden property.

    Another problem with accessing it via the Controller is that it's a bit more difficult because it's nested through a few other scopes. You can pass the event, grab the DOM node, and pull up it's scope, but that's a lot of irrelevant stuff in a Controller.

    The Solution:

    So instead, we can add a sibling directive, similar to the ngEnter example directive that you've included in the Codepen example. Perhaps something a bit more explicit so that it's a bit more obvious what it's doing:

    .directive('mdHideAutocompleteOnEnter', function () {
        return function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if(event.which === 13) {
                    scope.$apply(function (){
                        scope.$$childHead.$mdAutocompleteCtrl.hidden = true; // $scope  modified to scope
                    });
    
                    event.preventDefault();
                }
            });
        };
    });
    

    The HTML would simply include this directive when relevant:

    <md-autocomplete 
                   md-hide-autocomplete-on-enter
                   md-items="item in querySearch(searchText)"
                   md-item-text="item.name">
         <span md-highlight-text="searchText">{{item.name}} :: {{item.type}}</span>
    </md-autocomplete>
    

    Here's the example, modified with it in action: http://codepen.io/anon/pen/mJvGzp?editors=101

    0 讨论(0)
  • 2021-02-13 05:38

    The better way to access the controller methods is to target the element and then use the jqLite object to gain access to the controller:

    var $acElement = angular.element(document.getElementById('Auto'));
    var acCtrl = $acElement.controller('mdAutocomplete');
    acCtrl.hidden = true;
    

    Whenever you access anything using the scope() method on an angular element, your implementation will break if you ever want to disable angular debug info.

    0 讨论(0)
  • 2021-02-13 05:41

    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

    0 讨论(0)
  • 2021-02-13 05:51

    If you don't mind losing focus on the md-autocomplete input element on enter, you can close md-autocomplete suggestions without using hacky ways that involve messing with the internal $mdAutocompleteCtrl controller. This depends on md-autocomplete to automatically hide suggestions when the input element is no longer focused.

    1. Wrap your md-autocomplete element in a form (or use a directive like ng-enter) and add an ID to the input element using md-input-id
    
      <form ng-submit="vm.handleFormSubmit()">
        <md-autocomplete md-input-id="autocomplete" ...>
        </md-autocomplete>
      </form>
    
    
    1. Call blur() on the #autocomplete input element
    
    handleFormSubmit() {
      angular.element(document.querySelector('#autocomplete')).blur();
    }
    
    
    0 讨论(0)
提交回复
热议问题