AngularJS : filter and bold part of the result

All we need is an easy explanation of the problem, so here it is.

I have a list filtered like this:

ng-repeat="item in items | filter:query | limitTo:10"

and a search input

ng-model="search.name"

It works but I would like to make the query part in the results bold.

Example:

query = zza

results:

  • Li*zza*
  • Pi*zza*
  • Abc*zza*def

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can make your own custom filter that alters the input based on the search string :

angular.module('app').filter('searchfilter', function() {
    return function (input, query) {
        var r = RegExp('('+ query + ')', 'g');
        return input.replace(r, '<span class="super-class">$1</span>');
    }
});

This works, but the filter returns html, so you will need to tell angular to treat the result as html. In order to do this, you need to include ngSanitize as a module dependency and insert the result with ng-bind-html.
Here’s a complete demo :

<div ng-app="app">
  <div ng-controller="Ctrl">
      <input ng-model="search" placeholder="search a fruit" />
      <ul>
          <li ng-repeat="fruit in fruits| filter:search | limitTo:10" ng-bind-html="fruit | searchfilter:search" ></li>
      </ul>
  </div>
</div>

And the angular part :

angular
    .module('app', ['ngSanitize'])
    .controller('Ctrl', function($scope){
        $scope.fruits = 'apple orange banana pineaple grape plumb strawberry lemon lime'.split(' ');
    })
    .filter('searchfilter', function() {
        return function (input, query) {
            return input.replace(RegExp('('+ query + ')', 'g'), '<span class="super-class">$1</span>');           
        }
    });

Here’s the online demo: http://jsfiddle.net/gion_13/ZDWdH/2/.

Method 2

Two hints for the answer from gion_13.

If the query is a empty string (after filtering and then deleting the search term), then the input “apple” is modified like this:
apple

The solution for this is to change either the regex or a early return:

.filter('searchfilter', function() {
    return function (input, query) {
        if (query === '') {
            return input;
        }
        return input.replace(RegExp('('+ query + ')', 'g'), '<span class="super-    class">$1</span>');           
    }    
});

If you don’t want a case sensitive filter than change the RegExp:

RegExp('('+ query + ')', 'gi'), '<span class="super-    class">$1</span>');           

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply