Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a max length for the search input in (AngularJS) ui-select component?

Suppose I have the following (very basic) code for a 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>

Now, this generates all the html nodes, etc, which contain an input for searching and filtering the options displayed on the list.

The problem is:

How to set (in any variant) a maximum length for the input search ?

The directive doesn't offer any built-in data-attribute for doing so.

So, the expected behavior is: If I set a max length of 10 characters, when the user type/copy+paste a string larger than the specified length, the string in the input search, gets truncated (though, if you could provide me with some other solution which allows the user to input only certain numbers of characters in the input search, I would really appreciated)

I found this related question on SO, but it's not applicable for this case, since I have no way to access to the value which is being typed on the input search via an ng-model or similar.

like image 243
lealceldeiro Avatar asked Mar 14 '17 20:03

lealceldeiro


1 Answers

You can add a custom attribute directive to the ui-select directive, then search for the input.ui-select-search inside it, and finally add and HTML maxlength attribute... (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>

DIRECTIVE

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);
    }
  }
});

Probably it isn't the best solution, but as you say if ui-select doesn't support it, you have to do it by yourself...

like image 69
The.Bear Avatar answered Nov 14 '22 20:11

The.Bear