【问题标题】:How to set a max length for the search input in (AngularJS) ui-select component?如何为(AngularJS)ui-select组件中的搜索输入设置最大长度?
【发布时间】:2017-08-05 08:37:39
【问题描述】:

假设我有以下(非常基本的)ui-select 代码

<ui-select ng-model="vm.selected">
    <ui-select-match>
        <span ng-bind="$select.selected.label"></span>
    </ui-select-match>
    <ui-select-choices repeat="item in vm.items">
        <span ng-bind="item.label"></span>
    </ui-select-choices>
</ui-select>

现在,这会生成所有 html 节点等,其中包含用于搜索和过滤列表中显示的选项的输入。

问题是:

如何设置(在任何变体中)输入搜索的最大长度?

指令不提供任何用于这样做的内置数据属性。

因此,预期的行为是:如果我将最大长度设置为 10 个字符,当用户键入/复制+粘贴大于指定长度的字符串时,输入搜索中的字符串会被截断(但是,如果您可以为我提供一些其他解决方案,允许用户在输入搜索中仅输入特定数量的字符,我将不胜感激)

我找到了this related question on SO,但它不适用于这种情况,因为我无法通过ng-model 或类似方式访问在输入搜索中键入的值。

【问题讨论】:

    标签: javascript jquery html angularjs ui-select


    【解决方案1】:

    您可以在ui-select指令中添加自定义属性指令,然后在其中搜索input.ui-select-search,最后添加HTMLmaxlength属性...(PLUNKER

    HTML

    <ui-select ng-model="vm.selected" maxlen="15">
        <ui-select-match>
            <span ng-bind="$select.selected.label"></span>
        </ui-select-match>
        <ui-select-choices repeat="item in vm.items">
            <span ng-bind="item.label"></span>
        </ui-select-choices>
    </ui-select>
    

    指令

    app.directive('maxlen', function() {
      return {
        restrict: 'A',
        link: function(scope, element, attr) {
          var $uiSelect = angular.element(element[0].querySelector('.ui-select-search'));
          $uiSelect.attr("maxlength", attr.maxlen);
        }
      }
    });
    

    可能这不是最好的解决方案,但正如你所说,如果ui-select 不支持它,你必须自己做......

    【讨论】:

    • 感谢您的解决方案!我在想一些不如创建新指令那么戏剧化的事情,但考虑到 ui-select 的当前状态,这很好。
    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 2017-10-19
    • 2017-02-06
    • 1970-01-01
    • 2021-11-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多