使用angularJS过滤器在搜索结果中突出显示搜索文本 [英] Highlight search text in the search results using angularJS filter
问题描述
我有一个输入框,用于在显示的整体结果中过滤出结果.我有一个过滤器"startWith".现在,我需要突出显示在显示的搜索结果中的搜索文本angularJS.
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. Now, I need to highlight the search text among the search results displayed in angularJS.
例如,当我在搜索框中输入"o"时,它应突出显示所显示橙色的"O".
For e.g., when I type 'o' in the search box, it should highlight 'O' of the Orange displayed.
能否请您帮助我实现这一目标?
Could you please help me achieve this?
这是我的代码:
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>
推荐答案
只需通过一个函数运行输出,以检查您的搜索并将一个类添加到突出显示的部分.道具是由于 reg ex博客(我讨厌正则表达式,但效果很好)也 google
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>
这篇关于使用angularJS过滤器在搜索结果中突出显示搜索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!