如何使用orderBy过滤器按长度排序字符串?

时间:2017-04-06 09:07:41

标签: angularjs string typeahead

我有这个代码按预期工作,为我提供了所有以我输入的字母开头的项目:

<input name="search-bar" id="search-bar" type="text"  ng-model="search" 
typeahead="res.label for res in result | filter:$viewValue:startsWith | 
limitTo:20">

但我希望这些建议按label的长度排序,所以我尝试了两件事而没有任何运气:

第一次尝试

<input name="search-bar" id="search-bar" type="text" ng-model="search" 
typeahead="res.label for res in result | filter:$viewValue:startsWith | 
limitTo:20 | orderBy:'res.label'">

第二次尝试

<input name="search-bar" id="search-bar" type="text" ng-model="search"
typeahead="res.label for res in result | filter:$viewValue:startsWith | 
limitTo:20 | orderBy:'res.label.length'">

EDIT(控制器代码):

var url = "/data/list.json";
var items = $http.get(url).then(function(response){
        $scope.result = response.data; //result is filled with a static json containing all the data
        $scope.loading = false;
    });

JSON示例(来自/data/list.json):

[{"code":64,"label":"ALPAGA (64)"},{"code":44,"label":"ALPA (44)"}]

我错过了什么?

1 个答案:

答案 0 :(得分:2)

您可以使用此runnable fiddle demo中的自定义orderBy例程,也可以尝试直接与迭代对象属性进行交互的orderBy:'label.length'。这两种方法都应该以适当的方式为您服务。

视图

<div ng-controller="MyCtrl">
  <div ng-repeat="item in data | orderBy:orderByLength">
      {{ item.label }}
  </div>
</div>

AngularJS应用程序

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope) {
  $scope.data = [{
    "code": 64,
    "label": "ALPAGA (64)"
  }, {
    "code": 44,
    "label": "ALPA (44)"
  }, {
    "code": 24,
    "label": "ALPA (12344)"
  }, {
    "code": 48,
    "label": "ALPA (42324df)"
  }];

  $scope.orderByLength = function (item) {
      return item.label.length
  }
});