如何编写 angularjs 过滤器来搜索字符串片段/字符串序列 [英] How can I write an angularjs filter to search for string fragments/sequences of strings

查看:35
本文介绍了如何编写 angularjs 过滤器来搜索字符串片段/字符串序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 angularjs 自定义过滤器,用于检查一组国家/地区是否包含用户输入的搜索字符串.

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

字符串可以由一个字母(例如E")、n 个字母的片段(例如lan")或整个单词(例如England")组成.

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').

在每种情况下,都应返回包含该字母或该片段的所有国家/地区,因此E"将返回England"、Estonia"等,而lan"将返回England"、Ireland"等.

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 模板:

  1. HTML Template:

<input ng-model="filter.text" type="search" placeholder="Filter..."/>

<ul>
   <li ng-repeat="item in data | listfilter:filter.text">
</ul>

  • angularJS

  • 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;
    };
    }]);
    

  • 推荐答案

    比那简单多了,使用String.indexOf()函数:

    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);
    });
    

    您可能希望将两个字符串 .toLowerCase() 都转换为不区分大小写的匹配:

    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);
    });
    

    这篇关于如何编写 angularjs 过滤器来搜索字符串片段/字符串序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆