Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mark search string dynamically using angular.js

How can I mark my search pattern dynamically in my html?
Example:

SearchExample

I'm using angular and my html looks like this:

<div>
   <input type="text" ng-model="viewmodel.searchString"/>
   <!--Moving over all phrases-->
   <div ng-repeat="phrase in viewmodel.Phrases">
        {{phrase.title}}            
   </div>
</div>

I want the string matching pattern will be mark on every change in search string.

Can you help me?

like image 845
Dor Cohen Avatar asked Dec 15 '13 17:12

Dor Cohen


2 Answers

Angular UI is a great choice. You can also do it with filter like: http://embed.plnkr.co/XbCsxmfrgmdtOAeBZPUp/preview

The essence is as commented by @Hylianpuffball, dynamically create styled 'span' tags for the matches.

.filter('highlight', function($sce) {
  return function(text, phrase) {
    if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
      '<span class="highlighted">$1</span>')

    return $sce.trustAsHtml(text)
  }
})

And use it like:

<li ng-repeat="item in data | filter:search.title"
    ng-bind-html="item.title | highlight:search.title">
</li>
like image 156
tungd Avatar answered Nov 15 '22 17:11

tungd


Just in case that someone (like me a moment ago) needs this for angular2:

highlight-pipe.ts:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'highlightPipe'})
export class HighlightPipe implements PipeTransform{

  transform(text:string, filter:string) : any{
    if(filter){
      text = text.replace(new RegExp('('+filter+')', 'gi'), '<span class="highlighted">$1</span>');
    }
    return text;
  }
}

and use it like this:

at top of file:

import {HighlightPipe} from './highlight-pipe';

in template where 'yourText' is the original text and 'filter' is the part you want to highlight:

<div [innerHTML]="yourText | highlightPipe: filter"/>

in component:

pipes: [HighlightPipe]

EDIT: I updated it for RC 4 and created a plunker for testing: http://plnkr.co/edit/SeNsuwFUUqZIHllP9nT0?p=preview

like image 29
Björn Kechel Avatar answered Nov 15 '22 18:11

Björn Kechel