Search code examples
javascriptangularjsangular-ui-bootstraptypeaheadbootstrap-typeahead

AngularJS typeahead add custom sort by function


I'm trying to build a typeahead which should get a specified number of results and sort them by startswith.

This means if I do have the values: Alabama, Missouri, Maryland, Massachusetts, etc. and type in the input field "m" or "M" the order should be Maryland, Missouri, Massachusetts, Alabama.

Therefore my code looks like this:

<input class="input-large" type="text" ng-model="selected" 
  typeahead="state for state in states | filter:$viewValue | limitTo:8">

I tried by adding a custom filter function:

<input class="input-large" type="text" ng-model="selected" 
  typeahead="state for state in states | filter:$viewValue | orderBy:orderByStartsWith()| limitTo:8">

with the function:

$scope.orderByStartsWith = function() {
    return function(element){
        return element.toLowerCase().startsWith($scope.selected.toLowerCase()) ? 0 : 1;         
    }
};

This isn't working, because the scope value selected is not updating as shown in this JSFiddle

Is there any solution to get the desired order?


Solution

  • Pass the $viewValue to your order by function and use it to sort the results.

    <input class="input-large" type="text" ng-model="selected" typeahead="state for state in states | filter:$viewValue | orderBy:orderByStartsWith($viewValue) | limitTo:8">
    
     $scope.orderByStartsWith = function(viewValue) {
          return function(element){
            return element.toLowerCase().startsWith(viewValue.toLowerCase()) ? 0 : 1;           
          }
        };
    

    check the fiddle: http://jsfiddle.net/2umL5yqL/1/