Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write an angularjs filter to search for string fragments/sequences of strings

I'm trying to write an angularjs custom filter that checks whether an array of countries contains a search string entered by the user.

The string can consist of one letter (e.g. 'E'), or a fragment of n-letters (e.g. 'lan') or an entire word (e.g. 'England').

In every case, all countries containing that one letter or that fragment should be returned, so 'E' would return 'England', 'Estonia' etc. while 'lan' would return 'England', 'Ireland', etc.

So far my filter returns the entire country or single letters but I'm having difficulty with string fragments:

  1. HTML Template:

    <input ng-model="filter.text" type="search" placeholder="Filter..."/>
    
    <ul>
       <li ng-repeat="item in data | listfilter:filter.text">
    </ul>
    
  2. angularJS

    angular.module('sgComponents').filter('listfilter',[ function () {
    return function(items, searchText) {
        var filtered = [];            
    
        angular.forEach(items, function(item) {
            if(item.label === searchText) { // matches whole word, e.g. 'England'
                filtered.push(item);
            }
            var letters = item.label.split('');
            _.each(letters, function(letter) {
                if (letter === searchText) { // matches single letter, e.g. 'E'
                    console.log('pushing');
                    filtered.push(item);
                }
            });
            // code to match letter fragments, e.g. 'lan'
        });
        return filtered;
    };
    }]);
    
like image 597
Tone Avatar asked Oct 16 '13 13:10

Tone


People also ask

What is the correct way to apply filter in AngularJS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.

How does filter work in AngularJS?

The “filter” Filter in AngularJS is used to filter the array and object elements and return the filtered items. In other words, this filter selects a subset (a smaller array containing elements that meet the filter criteria) of an array from the original array.


1 Answers

It is much simpler than that, use the String.indexOf() function:

angular.forEach(items, function(item) {
    if( item.label.indexOf(searchText) >= 0 ) filtered.push(item);
});

You may want to turn both strings .toLowerCase() to do case-insensitive matching:

searchText = searchText.toLowerCase();
angular.forEach(items, function(item) {
    if( item.label.toLowerCase().indexOf(searchText) >= 0 ) filtered.push(item);
});
like image 51
Nikos Paraskevopoulos Avatar answered Oct 23 '22 00:10

Nikos Paraskevopoulos