【问题标题】:How to order strings by length with orderBy filter?如何使用 orderBy 过滤器按长度排序字符串?
【发布时间】:2017-04-06 09:07:41
【问题描述】:

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

<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'">

编辑(控制器代码):

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)"}]

我错过了什么?

【问题讨论】:

  • 显示控制器代码
  • @ManikandanVelayutham 已编辑!
  • 我认为你不需要使用'res',试试这个:orderBy:'label.length'"
  • 是的,您可以像这样使用 orderBy:'-label.length' 或 orderBy:'label.length'
  • 如果还是不行,可以试试比较长度的函数stackoverflow.com/questions/12040395/…

标签: angularjs string typeahead


【解决方案1】:

您可以使用自定义的orderBy 例程,就像在这个runnable fiddle demo 中一样,或者只是尝试直接与迭代对象属性交互的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
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多