0

正如https://github.com/angular/material/issues/2727所说,不能同时使用浮动标签和角材料的默认清除按钮功能。那么通过使用指令来实现这种行为的干净方法是什么?

4

1 回答 1

0

HTML

<md-autocomplete md-floating-label="LABEL"
                 md-selected-item="$ctrl.model" md-search-text="$ctrl.searchText"
                 md-selected-item-change="$ctrl.itemChanged($ctrl.model)"
                 md-items="item in $ctrl.items" clear-autocomplete
                 md-autoselect="true" required>
  /* whatever you need, e.g. <md-item-template> or <md-not-found> tags */
</md-autocomplete>

没有一个 $ctrl 属性必须按照它们在这里的方式命名,只要你喜欢就叫它们。

指示

angular
  .module('yourModule')
  .directive('clearAutocomplete', clearAutocomplete);

function clearAutocomplete($parse) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      const button = angular.element('<md-button>').addClass('clear-autocomplete');
      button.append('<i class="material-icons">clear</i>');
      element.append(button);

      let searchTextModel = $parse(attrs.mdSearchText);

      scope.$watch(searchTextModel, function(searchText) {
        if (searchText && searchText !== '' && searchText !== null) {
          button.addClass('visible');
        } else {
          button.removeClass('visible');
        }
      });

      button.on('click', function() {
        searchTextModel.assign(scope, undefined);
      });
    }
  }
}

CSS(当然是可选的)

.em-clear-autocomplete {
  position: absolute;
  transform: translate(0, -100%);
  right: 8px;
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s, opacity 0.25s linear;

  &.visible {
    visibility: visible;
    opacity: 1;
    cursor: pointer;
  }

  i {
    font-size: 20px;
  }
}

如果您使用 ES16 之前的版本,只需将letand替换constvar. 如果您在理解 $parse 时遇到问题,请查看官方文档:https ://docs.angularjs.org/api/ng/service/ $parse

非常感谢@sebastianhenneberg!

于 2016-05-02T14:04:13.433 回答