Highlight searched result in Angularjs App

Today I am going to create a demo where searched text will be highlighed from the paragraph. Since when any user come across any huge listing or big paragraph then searching helps him/her alot to make his task easier. It improves the user experience when a user type related keyword and its get highlighted from the big paragraph.

 

So the required demo we don't need to do much task while working with angularjs. For this demo we need to interect with only two files one with html where we will show some text in paragraph with a search box and other where angularjs related task will be performed. Let's proceed step by step.

Have a look on html part(index.html)

 

 
<body ng-app="highlightText">
<h1 class="text-center">Highlight text in AngularJS App.</h1>
 
<div class="container text-center" ng-controller="highlightText">
<input type="text" placeholder="Search" ng-model="search.text"><br><br>
 
<!-- with filter -->
<div ng-repeat="item in data | filter:search.text"
ng-bind-html="item.text | highlight:search.text">
</div>
</div>
</body>
 

 

In the above file we can see there is a ng-app directive, heading tag, a search box and a div where paragraph content will be shown.

Now lets have a look on code in app.js file.

 

 
angular.module('highlightText', [])
.controller('highlightText', function($scope) {
$scope.data = [
{ text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. " }
]
})
.filter('highlight', function($sce) {
return function(text, phrase) {
if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
'<span class="color-bg">$1</span>')

 

return $sce.trustAsHtml(text)
}
})
 

 

In the above file we have a very basic angular app created with its controller named hightlightText and a data variable which is showing in html page. And within the controller we have a method which takes the value from the search box and matched it within the paragraph with below regular expression. 

new RegExp('('+phrase+')', 'gi')

 

With these easy steps we can perform the task of highlighting the text from the paragraph.

 

Let me know your thoughts over the email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share with your friends. 

Thanks!!

You can download complete code from here. Download Code