AngularJS typeahead add custom sort by function

Viewed 1444

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?

1 Answers
Related