AngularJS typeahead add custom sort by function

I am trying to create a typeahead that should get a certain amount of results and sort them using startswith.

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

So 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 to add 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 function:

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

This does not work because the scope value is selectednot updated as shown in this JSFiddle

Is there any solution to get the desired order?

+4
1

$viewValue .

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

: http://jsfiddle.net/2umL5yqL/1/

+3

All Articles