简体   繁体   English

使用angularJS过滤器在搜索结果中突出显示搜索文本

[英]Highlight search text in the search results using angularJS filter

I've an input box which is used to filter out the results among the overall results displayed. 我有一个输入框,用于在显示的整体结果中过滤出结果。 I've a filter 'startWith' for that. 我有一个过滤器“ startWith”。 Now, I need to highlight the search text among the search results displayed in angularJS. 现在,我需要突出显示在angularJS中显示的搜索结果中的搜索文本。

For eg, when I type 'o' in the search box, it should highlight 'O' of the Orange displayed. 例如,当我在搜索框中键入“ o”时,它应突出显示所显示橙色的“ O”。

Could you please help me achieve this? 你能帮我实现这个吗?

Here's my code: 这是我的代码:

 var app = angular.module('myApp', []); app.controller('myCtrl', ['$scope', function($scope) { $scope.myData = [{ 'name': 'Orange' }, { 'name': 'Banana' }, { 'name': 'Mango' }, { 'name': 'Apple' }, { 'name': 'Pineapple' }]; $scope.startWith = function(actual, expected) { var lowerStr = (actual + "").toLowerCase(); return lowerStr.indexOf(expected.toLowerCase()) === 0; } }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <div id="parentDiv" ng-app="myApp" ng-controller="myCtrl"> <input type="text" ng-model="search.name" class="searchText" id="search_txt" placeholder="Search Data" /> <div id="childDiv"> <p ng-repeat="obj in myData | filter:search:startWith" >{{obj.name}}</p> </div> </div> 

Just run the output through a function to check against your search and add a class to the highlighted part. 只需通过一个函数运行输出以检查您的搜索并将一个类添加到突出显示的部分。 Props are due to this blog for the reg ex (I hate regex but they work well) also google 道具是由于该博客的正则表达式(我讨厌正则表达式,但它们工作良好)也谷歌

 var app = angular.module('myApp', []); app.controller('myCtrl', ['$scope', function($scope) { $scope.myData = [{ 'name': 'Orange' }, { 'name': 'Banana' }, { 'name': 'Mango' }, { 'name': 'Apple' }, { 'name': 'Pineapple' }]; $scope.startWith = function(actual, expected) { var lowerStr = (actual + "").toLowerCase(); return lowerStr.indexOf(expected.toLowerCase()) === 0; } $scope.highlight = function(text, phrase) { if (phrase) { text = text.replace(new RegExp('('+phrase+')', 'gi'), '<span class="highlighted">$1</span>') } return text; } }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <div id="parentDiv" ng-app="myApp" ng-controller="myCtrl"> <input type="text" ng-model="search.name" class="searchText" id="search_txt" placeholder="Search Data" /> <div id="childDiv"> <p ng-repeat="obj in myData | filter:search:startWith" >{{highlight(obj.name)}}</p> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM