Creating a search filter and text highlight feature in AngularJS can be achieved by following these steps

var app = angular.module('app',['ngSanitize']);

app.controller('searchCtrl',['$scope', function($scope){
  $scope.searchContents = [
{
title: 'Hedng one',
disc_1: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
},
{
title: 'Heading tow',
disc_1: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
disc_2: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
disc_3: 'lorem lorem lorem'
},
{
title: 'Heding three',
disc_1: 'discription..............................................'
},
{
title: 'Heding four',
disc_1: 'discription..............................................'
}
];
}]);

app.filter('highlight', function () {
  return function (text, search, caseSensitive) {
    if (text && (search || angular.isNumber(search))) {
      text = text.toString();
      search = search.toString();
      if (caseSensitive) {
        return text.split(search).join('<span class="ui-match">' + search + '</span>');
      } else {
        return text.replace(new RegExp(search, 'gi'), '<span class="ui-match">$&</span>');
      }
    } else {
      return text;
    }
  };
});
/* Generated by less 2.5.1 */
.ui-match {
  background: #FFC107;
  color: #fff;
}

.side-panel.panel-open {
  transform: translateX(0%);
  display: block;
}
.side-panel li {
  float: left;
  width: 100%;
}
.side-panel.side-panel-singlar {
  z-index: 10;
}


.search-results > ul {
  list-style: none;
  padding: 0;
  margin: 5%;
}
.search-results > li {
  line-height: 1.3em;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-sanitize.min.js"></script> 
<script type="text/javascript" src="js/script.js"></script> 
<link rel="stylesheet" type="text/css" href="js/style.css">
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div ng-app="app" ng-controller="searchCtrl">
  <div class="side-panel-singla">
    <input type="text" class="input-search" placeholder="Search..." ng-model="searchText" />
    <button class="btn-search">search</button>
    <div  ng-repeat="searchContent in searchContents | filter:searchText">
      <ul>
        <li>
          <h3 ng-bind-html="searchContent.title | highlight:searchText"></h3>
          <p ng-bind-html="searchContent.disc_1 | highlight:searchText"></p>
          <!-- Add logic here to expand paragraph when searched text is found -->
        </li>

      </ul>
    </div>
  </div>
  </div>
</body>
</html>
To enhance functionality, consider adding a feature that expands paragraphs only when the searched text is found within them. You can refer to a similar example implemented using AngularJS at this Fiddle Demo. Instead of Kendo, implement the expansion feature using AngularJS for an improved user experience.

Answer №1

Here is a specific solution tailored to your case. I defined a new class named hastext in the style sheet, and then included a lengthy ng-class directive within a new <div> wrapping the paragraph <p>s.

This method makes use of your highlight filter by comparing the filtered text with the original version, and setting it to true if any differences are detected (for instance, if it finds any inserted <span>s). However, adding more paragraphs will require additional lines in the ng-class call.

var app = angular.module('app',['ngSanitize']);

app.controller('searchCtrl',['$scope', function($scope){
  $scope.searchContents = [
{
title: 'Heading one',
disc_1: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
},
{
title: 'Heading two',
disc_1: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
disc_2: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
disc_3: 'lorem lorem lorem'
},
{
title: 'Heading three',
disc_1: 'description..............................................'
},
{
title: 'Heading four',
disc_1: 'description..............................................'
}
];
}]);

app.filter('highlight', function () {
  return function (text, search, caseSensitive) {
    if (text && (search || angular.isNumber(search))) {
      text = text.toString();
      search = search.toString();
      if (caseSensitive) {
        return text.split(search).join('<span class="ui-match">' + search + '</span>');
      } else {
        return text.replace(new RegExp(search, 'gi'), '<span class="ui-match">$&</span>');
      }
    } else {
      return text;
    }
  };
});
/* Generated by less 2.5.1 */
.ui-match {
  background: #FFC107;
  color: #fff;
}

.side-panel.panel-open {
  transform: translateX(0%);
  display: block;
}
.side-panel li {
  float: left;
  width: 100%;
}
.side-panel.side-panel-singular {
  z-index: 10;
}


.search-results > ul {
  list-style: none;
  padding: 0;
  margin: 5%;
}
.search-results > li {
  line-height: 1.3em;
}
.paragraphs {
  height: 0;
  overflow-y: hidden;
}
.paragraphs.hastext
{
   height: auto;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-sanitize.min.js"></script> 
<script type="text/javascript" src="js/script.js"></script> 
<link rel="stylesheet" type="text/css" href="js/style.css">
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div ng-app="app" ng-controller="searchCtrl">
  <div class="side-panel-singla">
    <input type="text" class="input-search" placeholder="Search..." ng-model="searchText" />
    <button class="btn-search">search</button>
    <div  ng-repeat="searchContent in searchContents" >
      <ul>
        <li>
          <h3 ng-bind-html="searchContent.title | highlight:searchText" ></h3>
          <div class="paragraphs" ng-class="{'hastext' : ((searchContent.title | highlight:searchText) != searchContent.title ||
            (searchContent.disc_1 | highlight:searchText) != searchContent.disc_1 ||
            (searchContent.disc_2 | highlight:searchText) != searchContent.disc_2
          )}">
            <p ng-bind-html="searchContent.disc_1 | highlight:searchText"></p>
            <p ng-bind-html="searchContent.disc_2 | highlight:searchText"></p>
           </div>
        </li>

      </ul>
    </div>
  </div>
  </div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging TypeScript's "this" keyword within an interface

I am currently working on a personalized interface where I aim to determine the type of an interface value within its implementation rather than in the interface definition, without using generics. It is important to note that these implementations will al ...

What is the best method for transferring array values from an input field to a function when the input

When selecting dates, the format that comes out is 02/01/2017-06/19/2017 as one value. However, I need to pass these selected values as two separate values to a function named "VizDateRange". How can I achieve this? //HTML <div class="input-group date ...

Adjust the size of CSS elements on hover while removing any margin

I am currently working on making my navigation bar elements larger when hovered over. However, I'm facing an issue where the rest of the website shifts downward slightly when I mouseover them, and it doesn't look good. Is there a way to increase ...

Determine if a Node.js Express promise holds any data

I'm looking for assistance with my nodejs application that returns a promise. What I need help with is figuring out how to determine if the result of this promise contains data or if it's just an empty array. I attempted using Object.keys(result) ...

Passing Events in JavaScript Explained

I'm struggling with a click event that involves setting a value. @foreach (var item in Model) { <button class="btn btn-small btn-danger btn-flat" type="button" onclick="SetDelete('@item.Id','@Html.Raw(item.Name)')"><i ...

Suggestions for correcting the placeholders' alignment in Bootstrap 5

Currently, I am in the process of creating a registration form and experiencing some issues with spacing and positioning. How can I adjust them to be aligned on the same line in a symmetrical manner? Below is the code snippet I have added along with an ima ...

Issues with the parseInt() Function

I'm having trouble figuring out why parseInt() isn't working correctly in my code, especially when passing numbers through to my function parameters. It keeps returning NaN in both my array and the function's return value. What I'm att ...

Running the Npm start command encounters an error

My terminal is showing the following error message: Q:\clone\node-cloudinary-instagram\node_modules\express\lib\router\route.js:202 throw new Error(msg); Error: Route.get() requires a callback function but go ...

What is the best way to eliminate empty space at the bottom of a page that is being caused by a button?

I have identified the reason for the blank space at the bottom of my page - it's due to a sticky "back to top" button. However, I am unsure how to resolve this issue. Here is the layout of the page: <nav> navbar </nav> <div> car ...

What is the process for excluding a file from running in jest?

Currently, I am working on integration tests using Jest and I have a folder with 20 test files. However, there are three specific files in that folder that should not be executed during the testing process. I tried using testPathIgnorePatterns, but it seem ...

Make the Angular Modal scrollable except for when a specific div is being click dragged

I am working on an Ionic app that uses AngularJS. One issue I encountered is with a modal popup that can sometimes extend beyond the visible area. To address this, we applied overflow: hidden to its CSS class. However, there is a specific functionality i ...

What is the best way to close ngx-simple-modal in angular7 when clicking outside of the modal component?

Can anyone help me with closing the modal in my angular7 app when the user clicks outside of the modal component? I have been using the ngx-simple-modal plugin, and I tried implementing the following code: this.SimpleModalService.addModal(LinkPopupCompone ...

Steps to toggle text color upon clicking and switch the color of another text

As a beginner with no Js knowledge, I am trying to achieve a specific function. I want to be able to change the color of text when it is clicked, but also have the previously clicked text return to its original color. <div class="mt-5 fi ...

Encountering Issues with Deploying Angular/Express Application on Heroku: Frontend Unable to Access API Endpoint

During the development phase, everything runs smoothly with localhost:4200 for the front-end and localhost:8080 for the back-end. After deployment, the front-end is displayed without any issues. However, there is a problem with fetching data from the API ...

Executing dynamic ng-click in combination with $compile results in triggering the click event twice with just one click

I have included dynamic HTML with a div element. In addition, I have dynamically bound ng-click to it like so: $('#likePulseButton' + item.nid).attr('ng-click', 'likePulseObject(' + item.nid + ')'); Upon doing thi ...

Adding a class to an element in Rails without using any HTML markup using jQuery

Is there a better method for adding a class after a selector without using the html markup div? $('#apple').append($('<div></div>').addClass('icon-spinner')); //Is there an alternative to '<div></di ...

Set a specific width for inline list items

When it comes to having list items with images on the left and text on the right, the issue arises when each image is of a different width. This can cause the text to not align vertically next to their respective images. Is there a way to ensure that t ...

Is there a way to verify if all the div elements are set to display as none?

If all div elements are set to display:none, I want to display a message saying "No result found" element.each(function(i, el) { if (all elements are set to display:none) { no result found } } <div class="a" data-key="a ...

Using JSON for saving HTML code

Currently delving into the world of AngularJS and thrilled about organizing data in JSON format. I have decided to create a practical application for hands-on learning. The app is an online magazine where I store the essential data for each article in art ...

Modify the content upon attaching a file

I am trying to update the text when a file is checked and the form is submitted. Below is my form: $(" #client-form input[type='file'], .webform-client-form input[type='file'], #contact-form input[type='file']").click(fun ...