首页 > 解决方案 > AngularJS过滤器只显示匹配的单词作为结果,而不是整个字符串

问题描述

是否可以在带有过滤器的 ng-repeat 中仅显示匹配的单词?

例如我有以下字符串

[
{text: 'This is first text from the array.'},
{text: 'Text in this array is dummy and it makes no sense'}, 
{text: 'AngularJS is very old framework'}
]

如果我搜索字符“fr”,那么我希望在列表中仅显示 ti 元素:数组中第一个字符串的“from”和最后一个字符串的“framework”。我不需要显示整个字符串。

结果应该是例如:

<li>from</li>
<li>framework</li>

在过滤器服务中,我尝试将 {text:} 值更新为等于匹配值,但它会更新原始对象数组;

这是我的 JSFiddle过滤器示例 JSFiddle

标签: angularjsangularjs-ng-repeatangularjs-filter

解决方案


它不是很好,但你可以试试这个,它几乎给了你想要的。我建议您在其他可以简洁高效的 ng-repeat 块中呈现搜索。

items.filter(list => {
        if (list.text.toLowerCase().includes(filterValue)) {
          let catchPattern = new RegExp('(\\w*' + filterValue + '\\w*)', 'gi');
          let matches = list.text.toLowerCase().match(catchPattern)
          if (!matches)
            return items;

          filterdArray.push({
            'text': matches,
            'id': list.id
          })
        }

      });

附上相同的小提琴: 从字符串中查找单词


推荐阅读