簡體   English   中英

AngularJS typeahead按功能添加自定義排序

[英]AngularJS typeahead add custom sort by function

我正在嘗試構建一個typeahead,它應該獲得指定數量的結果並按startwith排序。

這意味着如果我有價值觀:阿拉巴馬州,密蘇里州,馬里蘭州,馬薩諸塞州等,並輸入輸入字段“m”或“M”,順序應該是馬里蘭州,密蘇里州,馬薩諸塞州,阿拉巴馬州。

因此我的代碼如下所示:

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

我嘗試添加自定義過濾器功能:

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

功能:

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

這不起作用,因為selected的范圍值未更新,如此JSFiddle中所示

是否有任何解決方案可以獲得所需的訂單?

按功能將$ 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM