1

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.

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?

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>

1 Answer 1

0

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.