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

后端 未结 3 1546
闹比i
闹比i 2021-01-01 21:32

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 on

相关标签:
3条回答
  • 2021-01-01 21:39

    Take a look at the Angular-UI-Bootstrap directive for typeahead it does exactly what you want: http://angular-ui.github.io/bootstrap/#/typeahead

    0 讨论(0)
  • 2021-01-01 21:45

    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);
    });
    
    0 讨论(0)
  • 2021-01-01 21:50
    angular.module('sgComponents').filter('listfilter',[ function () {
        return function(items, searchText) {
            var filtered = []; 
            var regex = new RegExp(".*" + searchItem + ".*", "ig");
            angular.forEach(items, function(item) {
                if(regex.test(item)){
                    filtered.push(item);
                }
            });
            return filtered;
        }
    }]);
    
    0 讨论(0)
提交回复
热议问题