How can I mark my search pattern dynamically in my html?
Example:
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?
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With