ilija veselica
ilija veselica

Reputation: 9574

AngularJS select - match first characters

https://github.com/angular-ui/ui-select

This search plugin finds a match using 'LIKE %word%'. Possible to change it to 'LIKE word%' Example: If I type letter 'T' when searching states, currenty it returns following:
HI
ID
IL
IN
IA
MI
RI
...

I'd like it to return:
ID
IL
IN
IA

Upvotes: 2

Views: 1443

Answers (1)

Raj Kantaria
Raj Kantaria

Reputation: 326

You can achieve this functionality by using angular's custom filter. Something like:

app.filter('propsFilter', function() {
  return function(items, props) {
    var out = [];
    if (angular.isArray(items)) {
      items.forEach(function(item) {
        var keys = Object.keys(props);
        var prop = keys[0];
        var text = props[prop].toLowerCase();
        if (item[prop].toString().toLowerCase().indexOf(text) === 0) {
          out.push(item);
        }
      });
    } else {
      out = items;
    }
    return out;
  };
});

and pass this filter into out select2 declaration:

<ui-select ng-model="person.selected" theme="select2" class="form-control" title="Choose a person">
            <ui-select-match placeholder="Select or search a person in the list...">{{$select.selected.name}}</ui-select-match>
            <ui-select-choices repeat="item in people | propsFilter: {name:$select.search}">
              <div ng-bind-html="item.name | highlight: $select.search"></div>
              <small ng-bind-html="item.email | highlight: $select.search"></small>
            </ui-select-choices>
          </ui-select>

Here is the plunkr link you can refer:

Upvotes: 5

Related Questions