How can I order by closest match in angular using orderBy

In a directive ng-repeatthat processes a very long list. I have a search box that I want to filter by the closest match.

for example: if I have:

  • Hi how are you
  • hello how are you today
  • Hi brother

and I'm looking for "hello"

I want hello brother to appear first, as this is the least number of characters away from the search bar.

+4
source share
2 answers

If you want to make the number of characters more important, you can sort by the length of the string.

orderBy: 'string.length'

Here is an example of plunker. Which doesn't make much sense, but proves that it works.

.

,

app.filter('sortByLength', function() {

  return function(items) {
    items.sort(function (a, b) {    
      return (a.length > b.length ? 1 : -1);
    });
    return items;
  };
});

, .  .

app.filter('sortByMatch', function() {
  return function(items, searchString) {
    var re = new RegExp("[" + searchString + "]", "g"); 
    items.sort(function (a, b) { 

      if (!searchString) {
        return input;
      }
      var matchingCharsA = a.length - (a.match(re) || []).length; 
      var matchingCharsB = b.length - (b.match(re) || []).length;

      return (matchingCharsA > matchingCharsB ? 1 : -1);
    });
    return items;
  };
});

.

ng-repeat="item in.... | sortByMatch: searchString

, .

+2

, angularJS , :

ng-repeat="item in .... | filter:searchText"

, :

http://plnkr.co/edit/tsrFcgwV1npDsYNPeNrk?p=preview

angular.module('app', []).filter('order', function() {
  return function(input, text) {

    if (!text) {
      return input;
    }

    return input.sort(function(a, b) {
       // if a, b is string, or object, you can compare 
       // a.name or b.name
      var ret = a.localeCompare(b);
      return ret; 

    });
  };
});

, , .

angular.module('app', []).filter('order', function() {
  return function(input, text) {

    if (!text) {
      return input;
    }

    return input.sort(function(a, b) {

      return a.length - b.length;

    });
  };
});

:

ng-repeat="item in.... | filter:searchText | order:searchText"
+3

Source: https://habr.com/ru/post/1620972/


All Articles